当我使用自定义日期而不是现在时无法生成特定格式的日期

Can't produce a certain format of date when I use a customized date instead of now

我正在尝试将日期格式化为自定义日期。当我使用 datetime.datetime.now() 时,我得到了正确的日期格式。但是,我的目的是在使用 1980-01-22 而不是 now 时获得相同的格式。

import datetime

date_string = "1980-01-22"

item = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
print(item)

我得到的输出:

2021-05-04T09:52:04.010Z

如何在使用自定义日期时获得与 1980-01-22 而非 now 相同的日期格式?

这是您想要实现的目标吗?

date_string = "1980-01-22"
datetime.datetime.strptime(date_string, "%Y-%m-%d").isoformat(timespec="milliseconds")

输出

'1980-01-22T00:00:00.000'

MrFuppes 在评论中的建议是完成日期转换和格式化用例的最短方法。

另一种方法是使用 Python 模块 dateutil。这个模块有很大的灵活性,我一直在使用它。

使用dateutil.parser.parse:

from dateutil.parser import parse

# ISO FORMAT 
ISO_FORMAT_MICROS = "%Y-%m-%dT%H:%M:%S.%f%z"

# note the format of these strings
date_strings = ["1980-01-22", 
                "01-22-1980", 
                "January 22, 1980", 
                "1980 January 22"]

for date_string in date_strings:
    dt = parse(date_string).strftime(ISO_FORMAT_MICROS)
    
    # strip 3 milliseconds for the output and add the ZULU time zone designator
    iso_formatted_date = f'{dt[:-3]}Z'
    print(iso_formatted_date)
    # output
    1980-01-22T00:00:00.000Z
    1980-01-22T00:00:00.000Z
    1980-01-22T00:00:00.000Z
    1980-01-22T00:00:00.000Z

使用dateutil.parser.isoparse:

from dateutil.parser import isoparse
from dateutil.tz import *

dt = isoparse("1980-01-22").isoformat(timespec="milliseconds")
iso_formatted_date = f'{dt}Z'
print(iso_formatted_date)
# output
1980-01-22T00:00:00.000Z