如何将日期字符串转换为ISO8601标准?
作者:互联网
使用dateutil我能够生成类型的ISO8601
YYYY-MM-DDThh:mm:ssTZD但我希望格式’YYYY-MM-DDThh:mm:ss.sssTZD’例如’2015-05-13T18:05:55.320-07:00′
我的代码是
from datetime import datetime
from dateutil.parser import *
from dateutil.tz import *
import dateutil
import time
ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()
now = parse("11/10/09 11:20 PM")
now = now.replace(tzinfo=tzoffset('PDT', utc_offset))
输出是2009-11-10T23:20:00-07:00
我将如何得到像2009-11-10T23:20:00.000-07:00的输出
解决方法:
>>> now = datetime.now(tzoffset('EDT', -4*60*60))
>>> print(now.isoformat())
2015-05-15T07:08:34.478784-04:00
请注意,如果值为0,isoformat方法将省略微秒(如示例解析时间.如果输出中必须有派系秒,请在格式字符串中使用%f:
>>> print(now.strftime("%y-%m-%dT%H:%M:%S.%f%z"))
15-05-15T07:35:00.000000-0400
如果您需要毫秒,则必须编写自己的格式化例程:
def format_time_with_milliseconds(time):
fmt = "{time.year:04}-{time.month:02}-{time.day:02}T{time.hour:02}:{time.minute:02}:{time.second:02}.{millisecond:03}{tz}"
return fmt.format(time=time, millisecond=int(round(time.microsecond/1000)), tz=time.strftime("%z"))
标签:python,datetime,python-dateutil 来源: https://codeday.me/bug/20190717/1489471.html