【问题标题】:how to convert datetime with timezone to UTC datetime?如何将带时区的日期时间转换为 UTC 日期时间?
【发布时间】:2022-12-17 19:34:51
【问题描述】:

我有一个字符串日期时间作为 - '2022-12-07T13:30:14+00:00' 和 '2022-12-07T13:30:07.697000+00:00'

如何将 + 时区转换为 UTC 时间并在这两种情况下获得输出 - “2022-12-07T13:30:14.000Z”和“2022-12-07T13:30:07.697Z”

请帮忙。

【问题讨论】:

  • 这回答了你的问题了吗? How do I parse an ISO 8601-formatted date?
  • 不,它不是相同的输入字符串
  • 您所有的日期时间字符串都以 +00:00 结尾吗?或者其他抵消也存在?
  • 它也可以是任何偏移+05:30

标签: python datetime timezone python-datetime


【解决方案1】:

您可以使用fromisoformatisoformat。如果您有混合的 UTC 偏移量,请使用 astimezone 转换为 UTC。

from datetime import datetime, timezone

strings = ['2022-12-07T13:30:14+00:00', '2022-12-07T13:30:07.697000+00:00',
           '2022-12-07T13:30:14+01:00', '2022-12-07T13:30:07.697000+05:30']

for s in strings:
    print(
        datetime.fromisoformat(s)
            .astimezone(timezone.utc) # to UTC if input has other offset
            .isoformat(timespec="milliseconds") # consistent precision in output
            .replace("+00:00", "Z") # no "standard-way" to get Z for UTC
        )
    
# 2022-12-07T13:30:14.000Z
# 2022-12-07T13:30:07.697Z
# 2022-12-07T12:30:14.000Z
# 2022-12-07T08:00:07.697Z 

【讨论】:

  • 这会将“2022-12-07T13:30:14+05:30”转换为正确的 utc 时间吗?
  • @deepu2711 刚刚补充说;然后你需要转换。
猜你喜欢
  • 2014-01-24
  • 2019-08-31
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
相关资源
最近更新 更多