我有一个档案。在Python中,我希望将其创建时间转换为ISO时间(ISO 8601)字符串,同时保留它是在东部时区(ET)创建的事实。
如何获取文件的ctime并将其转换为指示东部时区的ISO时间字符串(并在必要时考虑日光节约时间)?
我有一个档案。在Python中,我希望将其创建时间转换为ISO时间(ISO 8601)字符串,同时保留它是在东部时区(ET)创建的事实。
如何获取文件的ctime并将其转换为指示东部时区的ISO时间字符串(并在必要时考虑日光节约时间)?
当前回答
对于那些正在寻找仅限约会的解决方案的人来说,它是:
import datetime
datetime.date.today().isoformat()
其他回答
对于那些正在寻找仅限约会的解决方案的人来说,它是:
import datetime
datetime.date.today().isoformat()
标准RFC-3339毫秒
我需要时间在这个格式的LoRa应用程序,所以我想出了这个,我希望它有帮助:
from datetime import datetime
from time import strftime
# Get the current time in the format: 2021-03-20T16:51:23.644+01:00
def rfc3339_time_ms():
datetime_now = datetime.utcnow()
# Remove the microseconds
datetime_now_ms = datetime_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
# Add the timezone as "+/-HHMM", and the colon in "+/-HH:MM"
datetime_now_ms_tz = datetime_now_ms + strftime("%z")
rfc3339_ms_now = datetime_now_ms_tz[:-2] + ":" + datetime_now_ms_tz[-2:]
# print(f"Current time in ms in RFC-3339 format: {rfc3339_ms_now}")
return rfc3339_ms_now
我找到了约会时间。文件中的Isoformat。它似乎做了你想要的:
datetime.isoformat([sep])
Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS
If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM
The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
在estani的精彩回答中加入一个小变化
本地到ISO 8601,带时区,没有微秒信息(Python 3):
import datetime, time
utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(microsecond=0, tzinfo=datetime.timezone(offset=utc_offset)).isoformat()
样例输出:
'2019-11-06T12:12:06-08:00'
经过测试,这个输出可以被Javascript Date和c# DateTime/DateTimeOffset解析
ISO 8601时间表示
国际标准ISO 8601描述了日期和时间的字符串表示形式。这种格式的两个简单示例是
2010-12-16 17:22:15
20101216T172215
(两者都代表2010年12月16日),但该格式还允许亚秒级的分辨率时间和指定时区。这种格式当然不是python特有的,但它很适合以可移植的格式存储日期和时间。关于这种格式的详细信息可以在Markus Kuhn的条目中找到。
我建议使用这种格式在文件中存储时间。
在这种表示中获取当前时间的一种方法是使用Python标准库中的time模块中的strftime:
>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'
你可以使用datetime类的strptime构造函数:
>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)
最健壮的是Egenix mxDateTime模块:
>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)
参考文献
Python时间模块文档 Python datetime类文档 Egenix mxDateTime类