时区转换
In [15]: from datetime import datetime
In [16]: import pytz
In [17]: dt_utc = datetime.utcnow()
In [18]: dt_utc
Out[18]: datetime.datetime(2024, 4, 13, 2, 37, 36, 549343)
In [19]: dt_utc = datetime.utcnow().replace(tzinfo=pytz.utc)
In [20]: dt_utc
Out[20]: datetime.datetime(2024, 4, 13, 2, 37, 50, 312182, tzinfo=<UTC>)
In [21]:
In [22]:
In [23]: dt_china = dt_utc.astimezone(pytz.timezone("Asia/Shanghai"))
In [24]: dt_china
Out[24]: datetime.datetime(2024, 4, 13, 10, 37, 50, 312182, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
In [25]:
In [26]:
In [27]: dt_china.astimezone(pytz.utc)
Out[27]: datetime.datetime(2024, 4, 13, 2, 37, 50, 312182, tzinfo=<UTC>)
In [28]:
字符串转时间
>>> from datetime import datetime
>>>
>>> dt = "2020-12-01T03:21:57.330Z"
>>>
>>> datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2020, 12, 1, 3, 21, 57, 330000, tzinfo=datetime.timezone.utc)
>>>