python - 日期时间:在 isoformat() 中强制微秒输出

标签 python datetime

我刚刚发布了一个关于 Google 云端硬盘日期格式的问题,实际上我找到了解决方案。本质上,Google Drive 文档声明它需要以 RFC 3339 格式指定日期。但是,即使毫秒为零,它也明确需要完整或长格式。有没有办法强制 datetime isoformat() 方法输出毫秒,即使为零?我宁愿不使用 strftime 强制执行我自己的日期时间规范,但如果唯一的解决方案是使用以下 strftime 格式,那就这样吧。

d.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")

最佳答案

如果您使用的是 Python 3.6+,则可以将 timespec 参数传递给 isoformat()

该函数最终调用 _format_time,您可以在其中查看参数支持的值:

specs = {
    'hours': '{:02d}',
    'minutes': '{:02d}:{:02d}',
    'seconds': '{:02d}:{:02d}:{:02d}',
    'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}',
    'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}'
}

这将强制呈现值,即使特定部分为零也是如此

关于python - 日期时间:在 isoformat() 中强制微秒输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630398/

相关文章:

python - 如何将文本放入输入行 : how to ask for user input on the command line while providing a 'default' answer that the user can edit or delete?

php: datetime() 2 个日期时间与 2 个变量之间的差异

python - 如何在 python 中将 datetime.date 对象转换为 datetime.datetime?

datetime - 为什么在修补/保存时日期/时间值解释不正确?

python - pandas-datareader 世界银行 API 损坏

python - numpy根据索引选择子矩阵

python - 在不同的计算机系统中使用python进行TCP套接字编程

javascript - 如何在 JavaScript 中将数字转换为日期

SQL - 仅更新日期()数据

python - xlsxwriter,openpyxl : 'Workbook' object has no attribute 'write'