Convert time from UTC to GMT with Python

隐身守侯 提交于 2020-06-28 06:25:08

问题


I'm writting a python app that convert YML files to static HTML pages for my blog (static site generator). I want to add an RSS feed. On a some place I read that the publication date must be:

<pubDate>Wed, 05 Jul 2017 18:38:23 GMT</pubDate>

But I have:

<pubDate>2017-07-05T18:38:23+00:00</pubDate>

The datetime API from Python is really cumbersome about these. How to convert the string 2017-07-05T18:38:23+00:00 to GMT?

Thanks in avanced.


回答1:


import datetime
basedate="2017-07-05T18:38:23+00:00"
formatfrom="%Y-%m-%dT%H:%M:%S+00:00"
formatto="%a %d %b %Y, %H:%M:%S GMT"
print datetime.datetime.strptime(basedate,formatfrom).strftime(formatto)

will return you the correct transcription : Wed 05 Jul 2017, 18:38:23 GMT

my source for the formats : http://strftime.org/




回答2:


While the other answers are correct, I always use arrow to deal with date time in python, it's very easy to use.

For you example, you can simply do

import arrow
utc = arrow.utcnow()
local = utc.to('US/Pacific')
local.format('YYYY-MM-DD HH:mm:ss ZZ')

The doc contains more information.




回答3:


I strongly suggest using dateutil which is a really powerful extension to datetime. It has a robust parser, that enables parsing any input format of datetime to a datetime object. Then you can reformat it to your desired output format.

This should answer your need:

from dateutil import parser

original_date = parser.parse("2017-07-05T18:38:23+00:00")
required_date = original_date.strftime("%a %d %b %Y, %H:%M:%S GMT")


来源:https://stackoverflow.com/questions/45448083/convert-time-from-utc-to-gmt-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!