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"
Related
I have some random dates with different timezones, they are in formats like this "07 Mar 2022 13:52:00 -0300", or they could be like this: "07 Mar 2022 11:12:00 -0700". I don't know which timezone exactly they will be coming from. How can I convert all of them to UTC time "0000Z"?
You can use standard module datetime for this.
Function strptime() (string parsing time) can convert string to object datetime using matching pattern. For your examples works pattern '%d %b %Y %H:%M:%S %z'
Next you can use .astimezone(datetime.timezone.utc) to convert to UTC.
And later you can format string with strftime() (string formatting time) using again pattern '%d %b %Y %H:%M:%S %z' (or you can skip %z)
Minimal working code:
import datetime
data = [
"07 Mar 2022 13:52:00 -0300",
"07 Mar 2022 11:12:00 -0700",
]
for item in data:
print('before str:', item)
dt = datetime.datetime.strptime(item, '%d %b %Y %H:%M:%S %z')
print('before dt :', dt)
dt = dt.astimezone(datetime.timezone.utc)
print('after dt :', dt)
print('after str:', dt.strftime('%d %b %Y %H:%M:%S %z'))
print('---')
Result:
before str: 07 Mar 2022 13:52:00 -0300
before dt : 2022-03-07 13:52:00-03:00
after dt : 2022-03-07 16:52:00+00:00
after str: 07 Mar 2022 16:52:00 +0000
---
before str: 07 Mar 2022 11:12:00 -0700
before dt : 2022-03-07 11:12:00-07:00
after dt : 2022-03-07 18:12:00+00:00
after str: 07 Mar 2022 18:12:00 +0000
---
I would suggest to import datetime, then use the following method to convert your time stamps into datetime objects (where str is the time stamp as a string): time_stamp = datetime.strptime(str, "%d %b %Y") (where the parameter after str gives information on the formatting; for details see here: https://www.programiz.com/python-programming/datetime/strptime).
After that, you can use datetime.astimezone() to convert this into another time zone.
I am getting this String:
a = "Wed Mar 06 2019 17:35:33 GMT-0500 (Ecuador Time)"
and i am trying to parse it in python with this code:
fecha = datetime.strptime(a , '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
But i am getting an error
ValueError: time data 'Wed Mar 06 2019 17:35:33 GMT-0500 (Ecuador Time)' does not match format '%a %b %d %Y %H:%M:%S GMT%z (%Z)'
what am i doing wrong? i've try a lot of settings for the date but still can get a solution my goal is to get a date object and save it into a MongoDatabase
The problem with the code is "(Ecuador Time)" is not in the format required to match "(%Z)".
To fix your code, you can just simply remove "(Ecuador Time)" from your string and remove your "(%Z)". Since you already have your GMT offset, it shouldn't matter too much.
This would leave your code as:
from datetime import datetime
a = "Wed Mar 06 2019 17:35:33 GMT-0500"
fetcha = datetime.strptime(a , '%a %b %d %Y %H:%M:%S GMT%z')
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
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.
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")