Have A Correct Datetime With Correct Timezone
Solution 1:
feedparser
does provide the original datetime string (just remove the _parsed
suffix from the attribute name), so if you know the format of the string, you can parse it into a tz-aware datetime object yourself.
For example, with your code, you can get the tz-aware object as such:
datetime.datetime.strptime(d.entries[0].published, '%a, %d %b %Y %H:%M:%S %z')
for more reference on strptime()
, see https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
EDIT: Since Python 2.x doesn't support %z
directive, use python-dateutil
instead
pip install python-dateutil
then
from dateutil importparserdatetime_rss= parser.parse(d.entries[0].published)
documentation at https://dateutil.readthedocs.org/en/latest/
Solution 2:
feedparser
returns time in UTC timezone. It is incorrect to apply time.mktime()
to it (unless your local timezone is UTC that it isn't). You should use calendar.timegm()
instead:
import calendar
from datetime import datetime
utc_tuple = d.entries[0].published_parsed
posix_timestamp = calendar.timegm(utc_tuple)
local_time_as_naive_datetime_object = datetime.frometimestamp(posix_timestamp) # assume non-"right" timezone
RSS feeds may use many different dates formats; I would leave the date parsing to feedparser
module.
If you want to get the local time as an aware datetime object:
from tzlocal import get_localzone # $ pip install tzlocal
local_timezone = get_localzone()
local_time = datetime.frometimestamp(posix_timestamp, local_timezone) # assume non-"right" timezone
Solution 3:
Try this:
>>>import os>>>os.environ['TZ'] = 'Europe/Paris'>>>time.tzset()>>>time.tzname
('CET', 'CEST')
Post a Comment for "Have A Correct Datetime With Correct Timezone"