【问题标题】:How to Convert "2021-08-17T20:03:36.480-07:00" to local time in Python?如何在 Python 中将“2021-08-17T20:03:36.480-07:00”转换为当地时间?
【发布时间】:2021-08-25 09:29:08
【问题描述】:

因此,“2021-08-17T20:03:36.480-07:00”作为字符串给出。我想把它转换成当地时间。

类似这样的 2020-01-06 00:00:00。

这是我之前尝试过的

from datetime import datetime

def convert_utc_local(utc_time):
    conv_time = ' '.join(utc_time.split("T"))
    return conv_time.astimezone(tzlocal())

错误来了

return utc_time.astimezone(tzlocal())
AttributeError: 'str' object has no attribute 'astimezone'"

所以对我有用的是:

def convert_utc_local(utc_time):
    to_zone = tz.gettz('Asia/Tokyo')
    
    iso_to_local = datetime.fromisoformat(utc_time).astimezone(to_zone)
    dt = str(iso_to_local.replace(tzinfo=None).isoformat(' ', timespec='seconds'))
    return dt

【问题讨论】:

  • 我相信你已经尝试了一些东西,对吧?请也发布您的尝试。并且另外尝试阅读How to Askminimal reproducible example
  • 查看文档,您会发现datetime.fromisoformat。现在与 astimezone 结合,你就有了:datetime.fromisoformat("2021-08-17T20:03:36.480-07:00").astimezone(None)...
  • 在给出minimal reproducible example 时,您应该包含 error,这可能与您将字符串视为日期时间的事实有关(您永远不会实际使用导入的datetime) 和tzlocal 没有定义。
  • @chixy 你想把2021-08-17T20:03:36.480-07:00 转换成2020-01-06 00:00:00 你是说这个还是我听不懂?
  • @Xitiz:在链接的问答中,iso 字符串没有指定 UTC 偏移量,因此 UTC 在接受的答案中明确设置为 tzinfo。如果你在这里做同样的事情,结果是不正确的。

标签: python python-3.x datetime


【解决方案1】:

使用datetime.fromisoformat。它提供了干净的代码和is efficient。还有可用的“逆”方法datetime.isoformat,它从日期时间对象返回一个字符串。

转换器可以写成单行:

from datetime import datetime

# iso_to_localdt converts an ISO8601 date/time string to datetime object,
# representing local time (OS setting).
iso_to_localdt = lambda t: datetime.fromisoformat(t).astimezone(None)

使用中:

dt = iso_to_localdt("2021-08-17T20:03:36.480-07:00")

print(repr(dt))
# datetime.datetime(2021, 8, 18, 5, 3, 36, 480000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'Mitteleuropäische Sommerzeit'))

print(dt.isoformat(' ', timespec='seconds'))
# 2021-08-18 05:03:36+02:00

# to get local time without the UTC offset specified, i.e. naive datetime:
print(str(dt.replace(tzinfo=None).isoformat(' ', timespec='seconds')))
# 2021-08-18 05:03:36

注意:您的时区可能不同。

【讨论】:

  • 通常1-liner写成one-liner
  • @MrFuppes 您的回答计算了 UTC 偏移量,因此它对我有用。
【解决方案2】:

在更改时区之前,您需要使用 strptime 将 conv_time 转换为 datetime 对象。然后,要更改格式,您只需使用 strftime。

例如:

from datetime import datetime
from dateutil import tz


def convert_utc_local(utc_time):
    time = datetime.strptime(utc_time, '%Y-%m-%dT%H:%M:%S.%f%z')
    # Convert time zone
    local_time = time.astimezone(tz.tzlocal())
    return local_time.strftime('%Y-%m-%d %H:%M')

print(convert_utc_local("2021-08-17T20:03:36.480-07:00"))

【讨论】:

  • 而不是拆分和加入,使用%Y-%m-%dT%H:%M:%S.%f%z会很棒吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2012-03-24
相关资源
最近更新 更多