包含时间的 ISO 8601 日期时间

Datetime to ISO 8601 with time included

datetime.isoformat() returns '2018-03-24T20:25:08.698812' and datetime.isocalendar() returns '(2018, 12, 6)'
但我需要的是 ISO 格式的日期和时间,还有像这样的 ISO 日历 '2018-12-06T20:25:08.698812'
如何获得 ISO 格式和 ISO 日历的日期时间?

d = datetime.datetime.now()
print(d.isoformat())
print(d.isocalendar())

这是从 A 到 B 的一种方式:

>>> import datetime
... 
... d = datetime.datetime.now()
... print(d)
... print(d.isoformat())
... print(d.isocalendar())
... 
... yr, weeknum, weekday = map(str, d.isocalendar())
... weeknum = '0' + weeknum if len(weeknum) == 1 else weeknum
... weekday = '0' + weekday
... '-'.join((yr, weeknum, weekday)) + d.isoformat()[10:]
... 
2018-03-24 22:01:33.781735
2018-03-24T22:01:33.781735
(2018, 12, 6)
'2018-12-06T22:01:33.781735'

功能上,

>>> def customiso(dt):
...     yr, weeknum, weekday = map(str, dt.isocalendar())
...     weeknum = '0' + weeknum if len(weeknum) == 1 else weeknum
...     weekday = '0' + weekday
...     return '-'.join((yr, weeknum, weekday)) + dt.isoformat()[10:]
... 

>>> customiso(d)
'2018-12-06T22:01:33.781735'

您可以构造如下格式:

代码:

def isocalendar_str(a_datetime):
    iso = a_datetime.isoformat()
    iso_cal = a_datetime.isocalendar()
    return "{:0>4}-{:0>2}-{:0>2}".format(*iso_cal) + iso[10:]

如果您使用的是 Python 3.5+,您可以通过以下方式稍微简化一下:

def isocalendar_str(a_datetime):
    iso = a_datetime.isoformat()
    iso_cal = a_datetime.isocalendar()
    return "{:0>4}-{:0>2}-{:0>2}{}".format(*iso_cal, iso[10:])

有关新解包功能的详细信息,请参阅PEP 448

测试代码:

d = dt.datetime.now()
print(d.isoformat())
print(d.isocalendar())

print(isocalendar_str(dt.datetime.now()))

结果:

2018-03-24T19:03:05.097419
(2018, 12, 6)
2018-12-06T19:03:05.097419