Python strptime ValueError: time data does not match format - python

I have added timezones to my datetime column in my postgreSQL DB.
Now I have the error above everytime I want to compare dates.
On some points I have JSON requests, datetime objects are passed as strings, so I need to parse them, with the additonal timezone info I get:
ValueError: time data '2018-05-02 11:52:26.108540+02:00'
does not match format '%Y-%m-%d %H:%M:%S.%f+%Z'
Earlier I had:
2018-05-02 11:52:26.108540
which worked perfectly with:
%Y-%m-%d %H:%M:%S.%f
The new information which has been added is: +02:00
In the strptime docu it is telling me to use %z or %Z but it does not work.
EDIT:
I am using Python 3

The issue is the offset +02:00 you need to remove the colon ':' then it will work:
In[48]:
dt.datetime.strptime('2018-05-02 11:52:26.108540+0200', '%Y-%m-%d %H:%M:%S.%f%z')
Out[48]: datetime.datetime(2018, 5, 2, 11, 52, 26, 108540, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
So you would need to go through all your datetime strings and remove this in order for strptime to parse it correctly

You need to remove the colon and use the small %z for this to work.
>>> s = '2018-05-02 11:52:26.108540+02:00'
>>> fmt = %Y-%m-%d %H:%M:%S.%f%z'
>>> time.strptime(s, fmt)
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=2, tm_hour=11, tm_min=52, tm_sec=26, tm_wday=2, tm_yday=122, tm_isdst=-1)

Related

Converting string (with timezone) to datetime in python

I aim to convert
stringtime = '2020-02-30 10:27:00+01:00'
so that I can compare it to
nowtime = datetime.datetime.utcnow()
using
if nowtime > stringtime:
print(1)
I tried strptime:
datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S')
But cannot find a format specification for the timezone in the strptime documentation.
I also tried
pandas.Timestamp(stringtime)
but I get ValueError: could not convert string to Timestamp.
How can this be done?
datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S%z')
Will give you the expected result %z is the format (Python3 only), however your original date is invalid as February doesnt have 30 days :)
First of all: Your stringtime is wrong, there exists no February 30th. ;)
You can achieve what you want with dateutil:
import dateutil.parser
stringtime = '2020-03-30 10:27:00+01:00'
dateutil.parser.isoparse(stringtime)
# datetime.datetime(2020, 3, 30, 10, 27, tzinfo=tzoffset(None, 3600))

Trouble converting to datetime object

I am trying to convert using strptime and for the life of me cannot figure this out
'07-17-2019 23:39 PM GMT-4' does not match format '%m-%d-%y %H:%M %p %z'
Thank you for any help
So far I've found that %y should be %Y. The best way to approach this is to test it a bit at a time. Like starting with datetime.strptime('07-17-2019', '%m-%d-%Y'). There's also something wrong with the GMT-4. %z will match -0400 fine, and %Z will match UTC, EST, and others, which might be better than an offset if you want to include daylight savings time, but it looks like that's all you get with strptime.
dateutil.parser.parse might provide you with more options and flexibility.
I found a way to do this, which is not super flexible, but should have a bit of give.
Firstly, a few points:
%y should be %Y, to match a 4-digit year.
Using a 24-hour time with AM/PM is confusing, so let's just ignore the AM/PM.
GMT-4 is not a standard timezone name, so we need to handle it manually.
#!/usr/bin/env python3
import datetime
s = '07-17-2019 23:39 PM GMT-4'
fmt = '%m-%d-%Y %H:%M' # Excludes AM/PM and timezone on purpose
words = s.split()
# Get just date and time as a string.
s_dt = ' '.join(words[:2])
# Convert date and time to datetime, tz-unaware.
unaware = datetime.datetime.strptime(s_dt, fmt)
# Get GMT offset as int - assumes whole hour.
gmt_offset = int(words[3].replace('GMT', ''))
# Convert GMT offset to timezone.
tz = datetime.timezone(datetime.timedelta(hours=gmt_offset))
# Add timezone to datetime
aware = unaware.replace(tzinfo=tz)
print(aware) # -> 2019-07-17 23:39:00-04:00
P.s. I used these to reverse-engineer a bit of it
tz = datetime.timezone(datetime.timedelta(hours=-4))
dt = datetime.datetime(2019, 7, 17, 23, 39, tzinfo=tz)

Convert python timezone aware datetime string to utc time

I have a Python datetime string that is timezone aware and need to convert it to UTC timestamp.
'2016-07-15T10:00:00-06:00'
Most of the SO links talks about getting the current datetime in UTC but not on converting the given datetime to UTC.
Hi this was a bit tricky, but here is my, probably far from perfect, answer:
[IN]
import datetime
import pytz
date_str = '2016-07-15T10:00:00-06:00'
# Have to get rid of that bothersome final colon for %z to work
datetime_object = datetime.datetime.strptime(date_str[:-3] + date_str[-2:],
'%Y-%m-%dT%H:%M:%S%z')
datetime_object.astimezone(pytz.utc)
[OUT]
datetime.datetime(2016, 7, 15, 16, 0, tzinfo=<UTC>)

how to convert date string(2016/5/7/ 4:25:00 PM) to date format to (2016-05-07 4:25:00) in python [duplicate]

This question already has answers here:
How to print a date in a regular format?
(25 answers)
Closed 6 years ago.
having trouble converting this string into a datetime this is what I tried so far in code:
import datetime
mystring = '2016/5/7/ 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)
it throws me errors and I search in the library and still can't figure it out what I have wrong in my format.
Please any help I'll gratly apreciate it
You can do it as:
import datetime
mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p")
dateobj
Out[1]: datetime.datetime(2016, 5, 7, 16, 25)
dateobj1 = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p").strftime("%Y-%m-%d %I:%M:%S")
dateobj1
Out[2]: '2016-05-07 04:25:00'
The issue you are having is that in order to convert a date object you first have to create a date object. This means that your formatting will have to match the current string format '2016/5/7 4:25:00 PM' = "%Y/%m/%d %H:%M:%S %p". So we can now create a date obj and then format it using strftime with your new format "%Y-%B-%dT%H:%M:%S-%H:%M".
import datetime
mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %H:%M:%S %p")
dateobj = datetime.datetime.strftime(dateobj, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)
the output recieved is a little funky, but it matches your format perfectly. Visit the datetime library to view the format codes and read up on strptime vs strftime. Good luck.
Output: 2016-May-07T04:25:00-04:25
I'm not sure where your format string came from, but it's wrong. It doesn't match your string format at all.
Take a look at the available options in the documentation.
You want this:
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d/ %I:%M:%S %p")
This will get you a date object. You can then do this to reformat it how you want:
dateobj.strftime("%Y-%m-%d %I:%M:%S")
A couple things that were wrong with yours:
You used %H twice. This resulted in an error saying it'd be redefined.
%B is full month name (ie. January). You have a numeral.
The -s are incorrect since you have /s.
The T is not in your string at all.
Easily with dateutil.parser.parse
>>> from dateutil.parser import parse
>>> d = parse('2016/5/7/ 4:25:00 PM')
>>> d.strftime("%Y-%B-%dT%H:%M:%S-%H:%M")
'2016-May-07T16:25:00-16:25'
>>> d.strftime("%Y-%m-%d %I:%M:%S")
'2016-05-07 04:25:00'

Converting dates in Python

I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!

Categories