如何将datetime对象格式化为带有毫秒的字符串?


当前回答

要获得以毫秒为单位的日期字符串,使用[:-3]修剪%f(微秒)的最后三位数字:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

或者稍短一点:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]

其他回答

python -c "from datetime import datetime; print str(datetime.now())[:-3]"
2017-02-09 10:06:37.006

使用[:-3]删除最后3个字符,因为%f代表微秒:

>>> from datetime import datetime
>>> datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]
'2013/12/04 16:50:03.141'

字段宽度格式规范

UNIX date命令允许指定%3将精度降低到3位:

$ date '+%Y-%m-%d %H:%M:%S.%3N'
2022-01-01 00:01:23.456

下面是一个自定义函数,它可以在Python中做到这一点:

from datetime import datetime

def strftime_(fmt: str, dt: datetime) -> str:
    tokens = fmt.split("%")
    tokens[1:] = [_format_token(dt, x) for x in tokens[1:]]
    return "".join(tokens)

def _format_token(dt: datetime, token: str) -> str:
    if len(token) == 0:
        return ""
    if token[0].isnumeric():
        width = int(token[0])
        s = dt.strftime(f"%{token[1]}")[:width]
        return f"{s}{token[2:]}"
    return dt.strftime(f"%{token}")

使用示例:

>>> strftime_("%Y-%m-%d %H:%M:%S.%3f", datetime.now())
'2022-01-01 00:01:23.456'

注:%%不支持。

import datetime

# convert string into date time format.

str_date = '2016-10-06 15:14:54.322989'
d_date = datetime.datetime.strptime(str_date , '%Y-%m-%d %H:%M:%S.%f')
print(d_date)
print(type(d_date)) # check d_date type.


# convert date time to regular format.

reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

<<<<<<输出>>>>>>>

2016-10-06 15:14:54.322989    
<class 'datetime.datetime'>    
06 October 2016 03:14:54 PM    
2016-10-06 03:14:54 PM    
2016-10-06 15:14:54

要获得以毫秒为单位的日期字符串,使用[:-3]修剪%f(微秒)的最后三位数字:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

或者稍短一点:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]