【问题标题】:datetime append GMT to the end of the string?datetime 将 GMT 附加到字符串的末尾?
【发布时间】:2020-08-19 06:18:36
【问题描述】:

我正在将 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 附加到字符串的末尾,但找不到返回正确格式的方法。

【问题讨论】:

  • 呃,看来你刚刚做到了……?我的意思是,您在末尾附加了GMT
  • 您想要的输出似乎具有相对于 UTC(“-04:00”)的时区偏移量,但是您使用 '%Y-%m-%d' 解析日期时间字符串。时区信息应该从哪里来?
  • 传递给strptime()data["Campaign_Start_Date"]的值是多少?
  • -04:00 is Time from GMT 可能更正,但只有您的本地时区。你想硬编码吗?
  • 那么你为什么写“我需要将 GMT 附加到字符串的末尾”而实际上你不想附加它?

标签: python date datetime time gmt


【解决方案1】:

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

【讨论】:

  • 这仍然有效地将时区硬编码到代码中。
  • @martineau,当然-我猜你必须在某个地方定义它。除非你采取例如你运行脚本的机器的设置,但这对我来说听起来很不可预测......
  • @MrFuppes 这完美!谢谢你。我接受了答案。
  • @Chique_Code:我想说,如果您确定输入数据的时区,您应该可以对其进行硬编码。但是,API 应该严格使用 UTC 或提供时区信息(至少 UTC 偏移量)。
猜你喜欢
  • 2022-12-11
  • 2014-03-06
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 2013-10-17
  • 2020-12-19
  • 2021-12-16
相关资源
最近更新 更多