python模块之time and datetime

柔情只为你懂 2022-01-05 10:47 380阅读 0赞

time

  1. # python3
  2. # coding = utf-8
  3. import time
  4. timestamp = time.time()
  5. print('timestamp:%s, type: %s' % (timestamp, type(timestamp)))
  6. # time.localtime() 默认使用 time.time()
  7. localtime = time.localtime()
  8. print('localtime:', localtime)
  9. print('current hour is:', localtime[3])
  10. print('current hour is:', localtime.tm_hour)
  11. # time.asctime() 默认使用 time.localtime()
  12. print('localtime_readable:', time.asctime())
  13. # time.ctime() 默认使用 time.time()
  14. print('localtime_readable:', time.ctime())
  15. # time.strftime 默认使用 time.localtime()
  16. print('localtime_formatted:', time.strftime('%Y-%m-%d %H:%M:%S'))
  17. # 将格式字符串转换为时间戳
  18. test_str = '2017-08-26 12:12:12'
  19. test_timestamp = time.mktime(time.strptime(test_str, '%Y-%m-%d %H:%M:%S'))
  20. print('test_timestamp:', test_timestamp)

输出:

timestamp:1505887820.714079, type:
localtime: time.struct_time(tm_year=2017, tm_mon=9, tm_mday=20, tm_hour=14, tm_min=10, tm_sec=20, tm_wday=2, tm_yday=263, tm_isdst=0)
current hour is: 14
current hour is: 14
localtime_readable: Wed Sep 20 14:10:20 2017
localtime_readable: Wed Sep 20 14:10:20 2017
localtime_formatted: 2017-09-20 14:10:20
test_timestamp: 1503720732.0

datetime

  1. # python3
  2. # coding = utf-8
  3. import datetime
  4. now = datetime.datetime.now()
  5. print('now:%s, type: %s' % (now, type(now)))
  6. print('now_replace',now.replace(hour=0, minute=0, second=0))
  7. print('now.day:', now.day)
  8. print('now_formatter:', now.strftime('%Y-%m-%d'))
  9. print('now_timestamp:', now.timestamp())
  10. print('old_time:', datetime.datetime(2015, 4, 29, 12, 20))
  11. print('midnight:', datetime.datetime.combine(datetime.date.today(), datetime.time.min))

输出:

now:2017-09-20 14:11:07.533828, type:
now_replace 2017-09-20 00:00:00.533828
now.day: 20
now_formatter: 2017-09-20
now_timestamp: 1505887867.533828
old_time: 2015-04-29 12:20:00
midnight: 2017-09-20 00:00:00

参考资料:

PYTHON-基础-时间日期处理小结

转载于:https://www.cnblogs.com/gattaca/p/7285550.html

发表评论

表情:
评论列表 (有 0 条评论,380人围观)

还没有评论,来说两句吧...

相关阅读

    相关 timedatetime模块

    1.在Python中表示时间的方式 1.1时间戳 > 时间戳(timestamp)方式:通常来说,时间戳表示从1970年1月1日00:00:00开始按秒计算的偏移量