Parse a Date in Python with datetime - python

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')

Related

How to convert timezone in number to UTC?

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.

How to fix ValueError time date does not match format when converting from string to datetime

Im trying to convert a string to datetime and keep getting the error: ValueError: time data 'Mon, 22 Apr 2019 17:04:38 +0200 (CEST)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
from datetime import datetime
s = "Mon, 22 Apr 2019 17:04:38 +0200 (CEST)"
d = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z %Z')
What am i missing?
%Z is generally used for converting into string format. In any case, it is the offset, not the name of the time zone.
The rest of your code is valid, however:
s = "Mon, 22 Apr 2019 17:04:38 +0200"
d = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z')
datetime only comes with the ability to parse UTC and whatever local time zone is listed in time.tzname. It can't match (CEST) because it doesn't know what timezone that is (It would also be redundant because you defined the timezone using the offset +0200).
You will need to implement your own (CEST) using datetime.tzinfo or by importing an external library like pytz or pendulum in order to parse (CEST) from a string into a datetime.timezone.
Also, don't forget to include parenthesis() in your match string.
This code passes, however, I do not know what happens to 'CEST' once it is converted into the string.
from datetime import datetime
tz = 'CEST'
s = "Mon, 22 Apr 2019 17:04:38 +0200 " + tz
d = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z ' + tz)

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.

String to Time Python strptime

I'm pulling the date value from gmail and trying to perform some functions on it. First I simply want to display it, but I can't even do that. See my code and error below.
from datetime import datetime
timeString = 'Sat, 2 Aug 2014 09:29:31 -0700'
myTime = datetime.strptime(timeString, '%m-%d-%Y %I:%M %p')
Here's the error I get. Do you think its the -0700 that's getting in the way?
ValueError: time data 'Sat, 2 Aug 2014 09:29:31 -0700' does not match format '%m-%d-%Y %I:%M %p'
As the error message suggests, you need to put the same format as your date string is in, I've not tried it, but something like this should work:
myTime = datetime.strptime(timeString, '%a, %d %b %Y %I:%M:%S %z')
Check here for complete details.

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