首页 > 解决方案 > 如何在 Python 中以 2020-01-13T09:25:19-0330 格式获取当前日期时间?

问题描述

这是什么日期格式 2020-01-13T09:25:19-0330?以及如何在 python 中以这种格式获取当前日期时间?

编辑:还要注意 last 之后只有 4 位数字-。我需要使用的 API 完全接受这种格式。

第二次编辑:从 api 的开发团队确认,最后 4 位数字是毫秒,前面有 0。例如,330 是毫秒,他们将其称为 0330。

标签: pythonpython-3.xdatetimedatetime-formatpython-datetime

解决方案


这是一种ISO 8601时间戳格式。

为了以该格式获取当前时间:

from datetime import datetime
print(datetime.now().isoformat())

在您的情况下,iso 格式被截断为秒,并且有一个时区:

from datetime import datetime, timezone, timedelta
tz = timezone(timedelta(hours=-3.5))
current_time = datetime.now(tz)
print(current_time.isoformat(timespec="seconds"))

-3.5UTC 偏移量在哪里。


如果你想使用系统的本地时区,你可以这样做:

from datetime import datetime, timezone, timedelta
current_time = datetime.now().astimezone()
print(current_time.isoformat(timespec="seconds"))

推荐阅读