datetime是否将GMT附加到字符串末尾



我正在将php代码迁移到Python中,遇到了datetime。我的代码:

date_raw = datetime.datetime.strptime(data["Campaign_Start_Date"], '%Y-%m-%d')
date_new = date_raw.strftime("%Y-%m-%d"+"T"+"%H:%M:%S GMT")
print(date_new)
# 2020-09-14T00:00:00 GMT

我想要的输出是:2020-09-14T00:00:00-04:00,所以我需要将GMT附加到字符串的末尾,但找不到返回正确格式的方法。

strptime不会自动从格式化为'%Y-%m-%d'的时间中知道时区,您必须包括它,例如

from datetime import datetime
import pytz
# parse the string
datestring = '2020-05-04'
date = datetime.strptime(datestring, '%Y-%m-%d')
# add a timezone info
tz = pytz.timezone('US/Eastern')
date_est = tz.localize(date)
# datetime.datetime(2020, 5, 4, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
print(date_est.isoformat())
# 2020-05-04T00:00:00-04:00

最新更新