如何根据当地时区和夏令时获取UTC + x
号?
示例:假设我们位于巴黎/法国时区。对于冬季日期时间(1月1日,00:55:23),我们期望0001
:
import datetime
print datetime.datetime(2018, 01, 01, 00, 55, 23).strftime('%z')
# empty string because the datetime is naive
# expecting 0001
对于夏季,我们期望0002
:
print datetime.datetime(2018, 07, 01, 00, 55, 23).strftime('%z')
# expecting 0002
答案 0 :(得分:1)
使用dateutil:
from dateutil import tz
from datetime import datetime
paris = tz.gettz('Europe/Paris')
dt1 = datetime(2018, 1, 1, 0, 55, 23, tzinfo=paris)
dt2 = datetime(2018, 7, 1, 0, 55, 23, tzinfo=paris)
print(dt1.strftime('%z')) # prints +0100
print(dt2.strftime('%z')) # prints +0200
或者,使用pytz:
from pytz import timezone
from datetime import datetime
paris = timezone('Europe/Paris')
dt1 = paris.localize(datetime(2018, 1, 1, 0, 55, 23))
dt2 = paris.localize(datetime(2018, 7, 1, 0, 55, 23))
print(dt1.strftime('%z')) # prints +0100
print(dt2.strftime('%z')) # prints +0200