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
ISO8601本地且无微秒:
Local to ISO 8601 without microsecond:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43
使用TimeZone信息将ISO转换为ISO8601(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
使用本地TimeZone将UTC转换为ISO 8601无需微秒的信息(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
ISO8601本地化并带有TimeZone信息(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
注意,这里有一个错误在世界标准时间使用 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屋!