python ISO 8601 日期格式

use*_*071 5 python iso8601 strftime

我正在尝试像这样格式化日期,

2015-12-02T12:57:17+00:00

这是我的代码

time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime())
Run Code Online (Sandbox Code Playgroud)

这给出了这个结果,

2015-12-02T12:57:17+0000

我看不到任何其他可以提供 +00:00 格式的 %z 变体?解决这个问题的正确方法是什么?

Max*_*ios 1

这对你有用:

将 UTC 日期时间字符串转换为本地日期时间

我复制了代码以使其更容易解决,无论如何我表明这是另一个人的答案。

from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print(datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z'))
print(datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z'))
print(datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z'))

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print(t)
print(t.astimezone(EST))
Run Code Online (Sandbox Code Playgroud)

我已经在我的 Python Notebook 中尝试过并且运行良好。