Python 中的 ISO 时间 (ISO 8601) [英] ISO time (ISO 8601) in Python
问题描述
我有一个文件.在 Python 中,我想将其创建时间转换为 ISO 时间 (ISO 8601) 字符串 同时保留它是在东部时区 (ET).
I have a file. In Python, I would like to take its creation time, and convert it to an ISO time (ISO 8601) string while preserving the fact that it was created in the Eastern Time Zone (ET).
如何获取文件的 ctime 并将其转换为指示东部时区的 ISO 时间字符串(并在必要时考虑夏令时)?
How do I take the file's ctime and convert it to an ISO time string that indicates the Eastern Time Zone (and takes into account daylight savings time, if necessary)?
推荐答案
ISO 8601 本地:
Local to ISO 8601:
import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748
UTC 到 ISO8601:
UTC to ISO 8601:
import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856
本地到 ISO 8601 无微秒:
Local to ISO 8601 without microsecond:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43
UTC 到 ISO 8601 和时区信息 (Python 3):
UTC to ISO 8601 with TimeZone information (Python 3):
import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00
UTC 到 ISO8601,本地时区信息没有微秒(Python 3):
UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):
import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00
本地到 ISO 8601 和时区信息 (Python 3):
Local to ISO 8601 with TimeZone information (Python 3):
import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00
请注意,在 UTC 时间使用 astimezone()
时有一个错误.这给出了错误的结果:
Notice there is a bug when using astimezone()
on utc time. This gives an incorrect result:
datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result
对于 Python 2,请参阅并使用 pytz.
For Python 2, see and use pytz.
这篇关于Python 中的 ISO 时间 (ISO 8601)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!