How to handle timezone offset when parsing date in Python? - python

I was looking at this reference but couldn't find how to handle the timezone offset (e.g. +0200) when parsing a string into date in Python.
My date string example is Thu Apr 17 10:50:39 2014 +0200.
If it were just Thu Apr 17 10:50:39 2014, the pattern %a %b %d %H:%M:%S %Y when using datetime.strptime.
Can I and how do I represent the offset in the date parse pattern?

There is no offset-template in the strptime-function, afaik. You could use dateutils for this one:
from dateutil.parser import parse
d=parse("Thu Apr 17 10:50:39 2014 +0200")

Related

How to parse time retrieved from Facebook Graph into 12 hour format?

When I pull events start times from Facebook Graph in comes in this form:
2017-09-26T18:00:00+0300
I'd like to convert it into readable format so I use this:
readable_event_date = dateutil.parser.parse(event_date).strftime('%a, %b %d %Y %H:%M:%S')
and it comes out like this:
Tue, 26 Sep 2017 18:00:00
Which is good but it loses the offset from UTC and I'd like it in AM PM format.
Thus, I would like it like this:
Tue, 26 Sep 2017 9:00 PM
To get into 12 hours format and keep offset from UTC for printing :
from dateutil.parser import parse
event_date = '2017-09-26T18:00:0+0300'
date = parse(event_date)
offset = date.tzinfo._offset
readable_event_date = (date + offset).strftime('%a, %b %d %Y %I:%M:%S %p')
print(readable_event_date)
Output:
'Tue, Sep 26 2017 09:00:00 PM'
It seems like what you want is this time, expressed in UTC, in the format '%a, %b %d %Y %I:%M:%S %p'. Luckily, all the information you need to do this is contained in the datetime object that you parsed, you just need to convert to UTC
Python 2.6+ or Python 3.3+:
The approach you've taken using dateutil will work for Python 2.6+ or Python 3.3.+ (and also works for a greater variety of datetime string formats):
from dateutil.parser import parse
# In Python 2.7, you need to use another one
from dateutil.tz import tzutc
UTC = tzutc()
dt_str = '2017-09-26T18:00:00+0300'
dt = parse(dt_str)
dt_utc = dt.astimezone(UTC) # Convert to UTC
print(dt_utc.strftime('%a, %b %d %Y %I:%M:%S %p'))
# Tue, Sep 26 2017 03:00:00 PM
One thing I notice is that the date you've provided, as far as I can tell, represents 3PM in UTC, not 9PM (as your example states). This is one reason you should use .astimezone(UTC) rather than some other approach.
If you want to include the time zone offset information, you can also use the %z parameter on the non-converted version of the datetime object.
print(dt.strftime('%a, %b %d %Y %I:%M:%S%z %p'))
# Tue, Sep 26 2017 06:00:00+0300 PM
This %z parameter may also be useful even if you are keeping it in UTC, because then you can at least be clear that the date the user is seeing is a UTC date.
Python 3.2+ only:
Given that you know the exact format of the input string, in Python 3.2+, you can achieve this same thing without pulling in dateutil, and it will almost certainly be faster (which may or may not be a concern for you).In your case here is how to rewrite the code so that it works with just the standard library:
from datetime import datetime, timezone
UTC = timezone.utc
dt_str = '2017-09-26T18:00:00+0300'
dt = datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%S%z')
dt_utc = dt.astimezone(UTC)
print(dt_utc.strftime('%a, %b %d %Y %I:%M:%S %p'))
# Tue, Sep 26 2017 03:00:00 PM
print(dt.strftime('%a, %b %d %Y %I:%M:%S%z %p'))
# Tue, Sep 26 2017 06:00:00+0300 PM

How to compare HTTP headers with time fields in Python?

I am using Python to construct a proxy server as an exercise and
I want to compare two different strings of time received from a server.
For example,
Date: Sun, 24 Nov 2013 18:34:30 GMT
Expires: Sat, 23 Nov 2013 18:34:30 GMT
How can I compare whether the expiry time is earlier than the current time? Do I have to parse it using the strptime method of the datetime module or is there an easier way to do so?
Convert each of the strings to a timestamp and compare these, for example as follows:
from datetime import datetime
date1 = "Date: Sun, 24 Nov 2013 18:34:30 GMT"
date2 = "Expires: Sat, 23 Nov 2013 18:34:30 GMT"
format = "%a, %d %b %Y %H:%M:%S %Z"
if datetime.strptime(date1, "Date: " + format) >= datetime.strptime(date2, "Expires: " + format):
print "Expired"

How to specify TimeZone in date formatting to get local time

I'm trying to compare two date values:
1) Jun 23, 2016 10:36:31 EET
2) Thu, 23 Jun 2016 07:36:31 GMT
To do this I need to convert second date to same date format as first one, so I use following code:
import datetime
date = datetime.datetime.strptime("Thu, 23 Jun 2016 07:36:31 GMT", "%a, %d %b %Y %H:%M:%S %Z")
.strftime('%b %d, %Y %H:%M:%S %Z')
and get following output:
Jun 23, 2016 07:36:31
This is still GMT time (also time zone value not specified)
How should I update my strftime argument to get Jun 23, 2016 10:36:31 EET as output?
P.S. EET is my local time zone
Here is the basic approach using the pytz module:
import datetime
import pytz
fmt = "%a, %d %b %Y %H:%M:%S %Z"
date = datetime.datetime.strptime("Thu, 23 Jun 2016 07:36:31 GMT", fmt)
gmt_date = pytz.timezone('GMT').localize(date)
print("Time in GMT:", gmt_date.strftime(fmt), sep='\n')
# Now to convert! Notice it took into account "summer time"
print("Time in EET",
gmt_date.astimezone(pytz.timezone('EET')).strftime(fmt), sep='\n')
My output:
Time in GMT:
Thu, 23 Jun 2016 07:36:31 GMT
Time in EET
Thu, 23 Jun 2016 10:36:31 EEST
Please read the docs, as working with timezones is tricky, and there are many caveats:
http://pytz.sourceforge.net/
AFAIK AM isn't a timezone. Did you try to get datetime.astimezone(tz)to work? https://docs.python.org/2/library/datetime.html
If you want to compare date-time values, it is much better to convert them both to datetime objects, e.g. call datetime.strptime on both of the input strings, each with the appropriate format string, and then compare the resulting datetime objects.

ValueError time data doesn't match the format

I am trying to match time zones with empty string in strptime function. Howevr, I get the following error.
ValueError: time data 'Thu Apr 14 01:46:29 MDT 2016' does not match format '%a %b %d %H:%M:%S %Y'
This is the code I try.
import datetime
d = datetime.datetime.strptime('Thu Apr 14 01:46:29 MDT 2016', '%a %b %d %H:%M:%S %Y')
How to map time-zone in python?
time zone can be MDT, MST,etc.
To parse this specific format (similar to rfc 822 used in emails), you could use email packages:
from email.utils import parsedate_tz, mktime_tz
time_tuple = parsedate_tz('Thu Apr 14 01:46:29 MDT 2016')
posix_time = mktime_tz(time_tuple)
Note: MDT is -6 hours here (according to the rfc 822). In general, timezone abbreviations may be ambiguous.
On Python 3.3+, you could create a timezone-aware datetime directly:
from email.utils import parsedate_to_datetime
dt = parsedate_to_datetime('Thu Apr 14 01:46:29 MDT 2016')
Here's how to parse it on earlier Python versions.

Parse CEST/CET time in python

I have these date strings:
Fri Oct 7 16:00:09 CEST 2011
I want to convert them to UTC. I have tried with this implementation:
def LocalToUtc(localtime):
return datetime.strptime(localtime, "%a %m %d %H:%M:%S %Z %Y").isoformat() + 'Z'
But I get a ValueError:
ValueError: time data 'Fri Oct 7 16:00:09 CEST 2011' does not match format '%a %m %d %H:%M:%S %Z %Y'
Any ideas?
Use the parsedatetime library.
There are two problems here:
You're using "%m" instead of "%b"
The standard lib can't parse "CEST", it understands only very few time zone names.
See also here: What possible values does datetime.strptime() accept for %Z?

Categories