英文:
convert datetime with timezone to proper format in python
问题
我有一个变量
date_1 = "2023-04-14T09:57:40-04:00"
如何转换为正确格式 - 2023-04-14T05:57:40Z
预期输出 - "2023-04-14T05:57:40Z"
英文:
I have a variable
date_1 = "2023-04-14T09:57:40-04:00"
how to convert to proper format - 2023-04-14T05:57:40Z
Expected ouput - "2023-04-14T05:57:40Z"
答案1
得分: 4
基本上,你想将带有UTC偏移的日期/时间字符串转换为UTC。你可以这样做
from datetime import datetime, timezone
date_1 = "2023-04-14T09:57:40-04:00"
utc = datetime.fromisoformat(date_1).astimezone(timezone.utc)
print(utc)
# 2023-04-14 13:57:40+00:00
print(utc.isoformat().replace("+00:00", "Z"))
# 2023-04-14T13:57:40Z
注:
- 类似-04:00的UTC偏移并非精确的时区;在特定时间,多个时区可能共享相同的UTC偏移量
- 正如Matt Johnson-Pint所评论的,UTC偏移量是从给定时间中减去以获得UTC,所以9点与-4小时偏移变为1点UTC
- 目前Python在格式化为字符串时无法直接将UTC表示为'Z',因此需要使用
replace
- datetime模块文档
英文:
Essentially, you're looking to convert a date/time string with a UTC offset to UTC. You can do that like
from datetime import datetime, timezone
date_1 = "2023-04-14T09:57:40-04:00"
utc = datetime.fromisoformat(date_1).astimezone(timezone.utc)
print(utc)
# 2023-04-14 13:57:40+00:00
print(utc.isoformat().replace("+00:00", "Z"))
# 2023-04-14T13:57:40Z
Notes:
- a UTC offset like -04:00 is not a time zone to be precise; multiple time zones can share the same UTC offset at a given time
- as Matt Johnson-Pint commented, UTC offsets are subtracted from the give time to get UTC, so 9 am with -4 hours offset becomes 1 pm UTC
- Python currently does not offer you to represent UTC as 'Z' when formatting to string, thus the
replace
- datetime module docs
答案2
得分: 0
请参考之前发布的其他答案,这个无法正确转换UTC时间。
英文:
Please refer to the other answer posted, this one does not properly convert UTC.
import datetime
import calendar
date_1 = '2023-04-14T09:57:40-04:00'
datex, timez=date_1[0:-6], date_1[-6:]
timed = datetime.datetime.strptime(datex, "%Y-%m-%dT%H:%M:%S")
timez = datetime.datetime.strptime(timez.replace(':',''), "%z")
output=datetime.datetime.fromtimestamp(calendar.timegm(timed.timetuple()), tz=timez.tzinfo).strftime("%Y-%m-%dT%H:%M:%SZ")
Code first splits datetime (datex
) and timezone (timez
). Converts datex
to datetime.datetime
then epoch, and convert timez
to datetime
. Finally converting datex
to UTC time based off current timezone, then formats the datetime.datetime
object to string.
Previous answer (not working)
import datetime
import calendar
date_1 = "2023-04-14T09:57:40-04:00"
timed = datetime.datetime.strptime(date_1, "%Y-%m-%dT%H:%M:%S%z")
output=datetime.datetime.fromtimestamp(calendar.timegm(timed.timetuple()), tz=timed.tzinfo).strftime("%Y-%m-%dT%H:%M:%SZ")
It's a bit long, but it should work!
The program first converts the date_1
to a datetime.datetime
object, then it converts it to epoch time, from which it converts this epoch time to the UTC timezone, and finally formats the epoch time to the output string.
Please let me know if this works for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论