如果用户未使用 Python datetime 设置微秒,如何将微秒设置为零?

How to set the microsecond to zero if not set by the user using Python datetime?

我正在尝试接收用户输入,并根据该字符串创建一个时间对象。像这样:

import datetime
user_input = '14:24:41.992181'
time = datetime.datetime.strptime(user_input, '%H:%M:%S.%f').time()

但是,如果 user_input'14:24:41',那么我会收到格式错误,这是可以理解的。我想要做的是对于这样的输入,时间对象的微秒精度将自动设置为 000000。我注意到使用 %z 对时区做了类似的事情,它内置在 strptime() 方法中。

执行此操作的理想方法是什么?

您可以使用 try/except 并处理用户输入与格式字符串不匹配的情况

import datetime
user_inputs = ['14:24:41.992181','14:24:41']
for user_input in user_inputs:
    try:
        dt = datetime.datetime.strptime(user_input, '%H:%M:%S.%f')
    except ValueError:
        dt = datetime.datetime.strptime(user_input, '%H:%M:%S')
    print(dt.strftime('%H:%M:%S.%f'))

输出

14:24:41.992181
14:24:41.000000

您可以 运行 对输入字符串的长度进行简单检查,假设您需要标准化输入。

user_input = '14:24:41'
if len(user_input) == 8:
    user_input += '.000000'
time = datetime.datetime.strptime(user_input, '%H:%M:%S.%f').time()