python - 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
推荐阅读
- python - sklearn 预测期间的异常:float() 参数必须是字符串或数字,而不是“dict”(错误代码:2)
- linq - 如何在一个 LINQ 查询中从父表和所有类型的子表中选择数据?
- sql - Moodle sql查询以获取已注册用户的已完成和未完成列表的报告
- c# - Scichart 图表未显示 xaxis 标签值
- pyspark-dataframes - 在 PySpark 中使用 Flashtext 进行关键字提取
- arrays - 复合配方
- javascript - 剑道网格按外部值突出显示所有列
- rest - 如何将 JAX-RS REST-Service 与 JNDI 查找集成到 SpringBoot 中?
- git - .gitignore 更改后 Git 拒绝拉取
- javascript - 我想测试路线是否存在