今天遇到一个关于使用python将rfc3339格式转为本地时区的情况:
2020-04-21T01:15:44.706Z
转为
2020-04-21 09:15:44
有两种方式:
- 使用pytz.timezone
from pytz import timezone
import datetime
def convert(rfc3339):
converted_date = datetime.datetime.fromtimestamp(datetime.datetime.strptime(rfc3339, '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=utc_tz).timestamp()).strftime('%Y-%m-%d %H:%M:%S')
return converted_date
rfc3339 = '2020-04-21T01:15:44.706Z'
utc_tz = timezone('UTC')
convert(rfc3339)
'2020-04-21 09:15:44'
- 使用dateutil.parser
from dateutil import parser
import datetime
def convert(rfc3339):
converted_date = datetime.datetime.fromtimestamp(parser.parse(rfc3339).timestamp()).strftime('%Y-%m-%d %H:%M:%S')
return converted_date
rfc3339 = '2020-04-21T01:15:44.706Z'
utc_tz = timezone('UTC')
convert(rfc3339)
'2020-04-21 09:15:44'
总体思路都差不多,重点都是先将rfc3339格式的字符串转为datetime.datetime对象时加入UTC时区信息,否则会导致UTC时间变为GMT+8:00
个人比较推荐第二种方法,dateutil貌似比较强大,可以多研究一下
>>> from dateutil import parser
>>> parser.parse("Tue Jun 22 07:46:22 EST 2010")
datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal())
>>> parser.parse('2020-04-21T01:15:44.706Z')
datetime.datetime(2020, 4, 21, 1, 15, 44, 706000, tzinfo=tzutc())
参考: