python - 将前导零添加到日期和时间字符串中的小时数

我有一个变量time = "12/13/2020 7:59",我想将字符串转换为"12/13/2020 07:59"(时间部分前带前导零)。

我不确定如何格式化它以使小时有两位数。

最佳答案

您可以信任 formatting options of datetime.datetime为你做到这一点:

from datetime import datetime

timestr = "12/13/2020 7:59"
    
dt = datetime.strptime(timestr, '%m/%d/%Y %H:%M')
corrected = datetime.strftime(dt, '%m/%d/%Y %H:%M')
    
print(corrected)
# 12/13/2020 07:59

正如文档所述,

When used with the strptime() method, the leading zero is optional for formats %d, %m, %H, %I, %M, [...].

因此 strptime 接受不带前导零的文本,但 strftime 会在将日期时间转回字符串时正确格式化它。

https://stackoverflow.com/questions/65287904/

相关文章:

css - react/next.js 中的 * 选择器

c# - 如何使用 MSIX 允许可编辑的 .Net 生成的配置文件?

amazon-web-services - 弹性 beantalk 未记录的 venv 路径

typescript - 如何使用 Jest 和 TypeScript 正确 stub /模拟 AW

docker - containerd 中的 docker volumes 是什么?

react-native - Expo 图像操纵器裁剪 - 根据 facedetector 值

python - 如何在 Python 的 Tkinter 中使用 .create_image

flutter - 有什么方法可以将查询参数插入 flutter web 中的命名路由?

bootstrap-modal - Bootstrap v5,如何在模式中传递变量(没有 jquer

gpu - Spacy + GPU 给出错误 : GPU is not accessible. 库是