datetime

作者: 噜噜迅儿 | 来源:发表于2018-06-06 23:11 被阅读0次
  • 获取当前日期和时间
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2018, 6, 6, 23, 13, 39, 365107)
  • 获取指定日期和时间
>>> from datetime import datetime
>>> datetime(2018, 6, 6, 22, 53)
datetime.datetime(2018, 6, 6, 22, 53)
  • datetime转换为timestamp
>>> from datetime import datetime
>>> datetime.now().timestamp()
1528298045.733604
  • timestamp转换为datetime
>>> from datetime import datetime
>>> t = 1528296947.481804
>>> datetime.fromtimestamp(t)
datetime.datetime(2018, 6, 6, 22, 55, 47, 481804)
  • str转换为datetime
>>> from datetime import datetime
>>> datetime.strptime('2018-6-6 22:57:33', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2018, 6, 6, 22, 57, 33)
  • datetime转换为str
>>> from datetime import datetime
>>> now = datetime.now()
>>> s = now.strftime('%Y-%m-%d %H:%M:%S')
>>> s
'2018-06-06 23:15:03'
>>> type(s)
<class 'str'>
  • datetime加减
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now + timedelta(days=1, hours=1)
datetime.datetime(2018, 6, 8, 0, 15, 15, 895960)
  • 本地时间转换为utc时间
>>> from datetime import datetime, timezone, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2018, 6, 6, 23, 15, 26, 394460)
>>> tz_utc_8 = timezone(timedelta(hours=8))
>>> now.replace(tzinfo=tz_utc_8)
datetime.datetime(2018, 6, 6, 23, 15, 26, 394460, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))
  • 时区转换
>>> from datetime import datetime, timezone, timedelta
>>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
>>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
>>> tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
>>> tokyo_dt1 = bj_dt.astimezone(timezone(timedelta(hours=9)))
>>> tokyo_dt
datetime.datetime(2018, 6, 7, 0, 16, 10, 201803, tzinfo=datetime.timezone(datetime.timedelta(0, 32400)))
>>> tokyo_dt1
datetime.datetime(2018, 6, 7, 0, 16, 10, 201803, tzinfo=datetime.timezone(datetime.timedelta(0, 32400)))

相关文章

网友评论

      本文标题:datetime

      本文链接:https://www.haomeiwen.com/subject/tmaisftx.html