![](/img/trans.png)
[英]How to convert '2021-08-24T11:00:19Z' to datetime and find days between it and the current time in django
[英]How to Convert "2021-08-17T20:03:36.480-07:00" to local time in Python?
因此,“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
在更改時區之前,您需要使用 strptime 將 conv_time 轉換為 datetime object。 然后,要更改格式,您只需使用 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"))
使用datetime.fromisoformat 。 它提供干凈的代碼並且高效。 還有可用的“反向”方法datetime.isoformat ,它從日期時間 object 返回一個字符串。
轉換器可以寫成一行:
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
注意:您的時區可能不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.