我有一个档案。在Python中,我希望将其创建时间转换为ISO时间(ISO 8601)字符串,同时保留它是在东部时区(ET)创建的事实。
如何获取文件的ctime并将其转换为指示东部时区的ISO时间字符串(并在必要时考虑日光节约时间)?
我有一个档案。在Python中,我希望将其创建时间转换为ISO时间(ISO 8601)字符串,同时保留它是在东部时区(ET)创建的事实。
如何获取文件的ctime并将其转换为指示东部时区的ISO时间字符串(并在必要时考虑日光节约时间)?
当前回答
在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解析
其他回答
对于那些正在寻找仅限约会的解决方案的人来说,它是:
import datetime
datetime.date.today().isoformat()
我找到了约会时间。文件中的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'
我开发了这个函数:
def iso_8601_format(dt):
"""YYYY-MM-DDThh:mm:ssTZD (1997-07-16T19:20:30-03:00)"""
if dt is None:
return ""
fmt_datetime = dt.strftime('%Y-%m-%dT%H:%M:%S')
tz = dt.utcoffset()
if tz is None:
fmt_timezone = "+00:00"
else:
fmt_timezone = str.format('{0:+06.2f}', float(tz.total_seconds() / 3600))
return fmt_datetime + fmt_timezone
在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解析
我同意Jarek的观点,而且我还注意到ISO偏移分隔符字符是冒号,所以我认为最终的答案应该是:
isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')