【问题标题】:ISO time to Human readable time in pythonISO时间到python中的人类可读时间
【发布时间】:2020-09-10 03:41:52
【问题描述】:

我正在使用 Python。我的时间格式是这样的

2020-05-23T06:35:11.418279Z #May 23, 2020 at 12:05:11 PM GMT+05:30

我想转换成人类可读的时间

23-05-2020 12:05 PM

我也试过解析器。但是没有效果。

谁能帮我解决这个问题?

提前致谢:)

【问题讨论】:

  • 这能回答你的问题吗? How do I parse an ISO 8601-formatted date?
  • ISO 时间完全是人类可读的。但是,您的问题是您想将时区转换为 GMT+5。为此,我建议使用pytz 模块。
  • 我尝试过使用 dateutil.parser
  • @Błotosmętek 但我不想显示 T 和毫秒

标签: python datetime epoch strptime strftime


【解决方案1】:

另见How do I parse an ISO 8601-formatted date?

不幸的是,由于Z,无法使用built-in fromisoformat(Python 3.7+)直接解析字符串“2020-05-23T06:35:11.418279Z”。您可以改用strptime,或this workaround,或dateutil 的解析器。例如:

from datetime import datetime
import dateutil

s = '2020-05-23T06:35:11.418279Z'

### parsing options
# strptime
dt = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')
# alternatively fromisoformat with replace (most efficient)
dt = datetime.fromisoformat(s.replace('Z', '+00:00'))
# or more convenient and a bit less efficient:
dt = dateutil.parser.isoparse(s)

# change timezone to Indian Standard Time:
dt = dt.astimezone(dateutil.tz.gettz('Asia/Kolkata'))
# datetime.datetime(2020, 5, 23, 12, 5, 11, 418279, tzinfo=tzfile('Asia/Calcutta'))

# note for Python 3.9+:
# use zoneinfo from the standard lib to get timezone objects

# now format to string with desired format
s_out = dt.strftime('%Y-%m-%d %I:%M %p')
s_out
# '2020-05-23 12:05 PM' 

【讨论】:

  • 那应该是 %I 而不是 %H 以获得 12 小时制。
  • 要获得 24 小时制时钟,请使用 %Y-%m-%d %H:%M 表示 strftime
【解决方案2】:
import datetime, pytz
isodate = '2020-05-23T06:35:11.418279Z'
d = datetime.datetime.fromisoformat(isodate[:-1]).replace(tzinfo=pytz.utc) # we need to strip 'Z' before parsing
print(d.astimezone(pytz.timezone('Asia/Kolkata')).strftime('%d-%m-%Y %I:%M %p'))

【讨论】:

  • 它工作得很好,非常感谢。但是 isodate[:-1] 是什么意思
  • isodate[:-1]isodate 没有最后一个字符(即Z,不符合严格的ISO格式)
  • 我还有一个疑问。不要误会我。因为这些时间的东西让我很困惑。我们正在添加 timezonr('Asia/Kolkata')。如果假设我的客户来自美国或欧洲。
  • 然后使用适当的时区。你想要GMT+05:30,那是印度时间。您可以通过print(pytz.all_timezones)查看可用时区名称列表
猜你喜欢
  • 2011-05-26
  • 2011-01-10
  • 1970-01-01
  • 2021-03-30
  • 2015-04-06
  • 2011-03-22
  • 2022-01-10
  • 1970-01-01
  • 2011-07-21
相关资源
最近更新 更多