分享

python3 datetime和time获取当前日期和时间

 hdzgx 2020-01-06

时间相关的包和函数import datetime

  1. import time
  2. # 获取当前时间, 其中中包含了year, month, hour, 需要import datetime
  3. today = datetime.date.today()
  4. print(today)
  5. print(today.year)
  6. print(today.month)
  7. print(today.day)
  8. '''
  9. >>>2017-01-01
  10. >>>2017
  11. >>>1
  12. >>>1
  13. '''
  14. # 获得明天, 其他依次类推
  15. tomorrow = today + datetime.timedelta(days=1)
  16. print(tomorrow)
  17. '''
  18. >>>2017-01-02
  19. '''
  20. # 时间相减,相加同理
  21. now = datetime.timedelta(days=0, hours=0, minutes=3, seconds=50);
  22. pre = datetime.timedelta(days=0, hours=0, minutes=1, seconds=10);
  23. duration_sec = (now - pre).seconds
  24. duration_day = (now - pre).days
  25. print(type(duration_sec))
  26. print(type(now - pre))
  27. print(duration_sec)
  28. print(duration_day)
  29. '''
  30. >>><class 'int'>
  31. >>><class 'datetime.timedelta'>
  32. >>>160
  33. >>>0
  34. '''
  35. # 使用time.strftime(format, p_tuple)获取当前时间,需要import time
  36. now = time.strftime("%H:%M:%S")
  37. print(now)
  38. '''
  39. >>>23:49:34
  40. '''
  41. # 使用datetime.now()
  42. now = datetime.datetime.now()
  43. print(now)
  44. print(now.year)
  45. print(now.month)
  46. print(now.day)
  47. print(now.hour)
  48. print(now.minute)
  49. print(now.second)
  50. print(now.microsecond)
  51. '''
  52. >>>2017-01-01 23:49:34.789292
  53. >>>2017
  54. >>>1
  55. >>>1
  56. >>>23
  57. >>>49
  58. >>>34
  59. >>>789292
  60. '''
文档地址:datetime — Basic date and time types

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多