【问题标题】:Python datetimezone formatPython 日期时区格式
【发布时间】:2020-07-25 11:08:08
【问题描述】:

我在 Python 中有以下格式的日期 "2020-03-22T03:15:05+00:00"。我需要将其转换为"%Y-%m-%d %H:%m:%s"。我正在尝试使用dateutil 执行此操作,但找不到任何东西。

谁能帮忙

d = "2020-03-22T03:15:05+00:00"

print(d)

t = dateutil.parser.parse(d)    

time = t.strftime('%Y-%m-%d')

我需要一些想法来从上面的代码中提取日期和时间

【问题讨论】:

标签: python python-3.x datetime


【解决方案1】:

您可以使用标准库中的datetime.strptime() 加上datetime.strftime()

>>> import datetime as dt
>>> d = "2020-03-22T03:15:05+00:00"
>>> t = dt.datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z")
>>> t
datetime.datetime(2020, 3, 22, 3, 15, 5, tzinfo=datetime.timezone.utc)
>>> t.strftime("%Y-%m-%d %H:%M:%S")
'2020-03-22 03:15:05'

【讨论】:

  • 在 Python 3.7 中,ISO 8601 字符串解析有一个专用方法:fromisoformat
  • 是的@Jérôme,确实如此。但是,在这种情况下,假定用户正在解析严格且已知的输入格式。因此,使用_parse_isoformat_date 可能会运行大量代码分支。
  • 好点。如果性能很重要,在这种情况下手动指定格式是有意义的。
【解决方案2】:

Python 3.7 引入了fromisoformat

import datetime as dt

d = "2020-03-22T03:15:05+00:00"
dt.datetime.fromisoformat(d).strftime("%Y-%m-%d %H:%M:%S")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-28
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多