包含时间的ISO 8601的日期时间

时间:2018-03-25 01:49:08

标签: python datetime iso iso8601

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

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

2 个答案:

答案 0 :(得分:3)

您可以构建如下格式:

代码:

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

答案 1 :(得分:2)

这是从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'