打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

时间相关的包和函数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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python日期和时间实例解读,Python计算时间差
时间模块日期模块--python
日期差的计算方法(date/time/python)
python日期和时间的操作方法汇总
Python的datetime模块分析
python时间转换字符串的方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服