首页 > 解决方案 > 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 附加到字符串的末尾,但找不到返回正确格式的方法。

标签: pythondatedatetimetimegmt

解决方案


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

推荐阅读