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

问题描述

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

已编辑:还请注意,最后-后仅4位数字。我需要点击的API完全接受这种格式。

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

解决方法

这是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.5是UTC偏移量。


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

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