Error converting datetime string to datetime object - python

I get an error when I try to convert a datetime string to a datetime object:
df['R_DATE'] = pd.to_datetime(df['R_DATE'], format='%a %b %d %H:%M:%S %Z %Y')
Error is:
...
File "pandas\_libs\tslibs\strptime.pyx", line 141, in pandas._libs.tslibs.strptime.array_strptime
ValueError: time data 'Mon Oct 18 00:00:00 EDT 2021'
does not match format '%a %b %d %H:%M:%S %Z %Y' (match)
From what I can tell format appears to match the datetime string value. I'm not sure if the timezone value (EDT) is causing issues.

nvm. found the answer I was looking for.
import dateutil
tzdict = {'EST': dateutil.tz.gettz('America/New_York'),
'EDT': dateutil.tz.gettz('America/New_York')}
df['R_DATE'] = df['R_DATE'].apply(dateutil.parser.parse, tzinfos=tzdict)

Related

How to strip date time in python

From a website I'm getting a date in such format: Sun Jan 22 21:32:58 +0000 2012. I understand that I must get rid of +0000 to convert it to the date, but how exactly I can do it? I read the documentation but my code is not working:
from datetime import datetime
strDate = 'Mon Apr 29 14:30:53 2019'
objDate = datetime.strptime(strDate, '%a %b %H %M %S %Y')
I'm getting an error:
ValueError: time data 'Mon Apr 29 14:30:53 2019' does not match format '%d %m %H %M %S %Y'
And I don't really understand why. Or anyone knows how I can get a date from Sun Jan 22 21:32:58 +0000 2012?
If your object is datetime.datetime you can just simply do date()
from datetime import datetime
datetime1 = datetime.now()
date1 = datetime1.date()
One line solution:
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S +%f %Y')
print(objDate)
#2019-04-29 14:30:53
Details:
You just forgot to use %d in order to capture the date number and the : for the time and you ALSO need to capture +0000.
Proof:
I'm afraid that the currently accepted answer, by seralouk, is incorrect. Using "+%f" turns the numbers into fractions of seconds. It's fine for 0000, but will mess things up if they happen to be anything else.
This is because the "+0000" part is a time zone offset, and the proper way to parse it is by using the "%z" directive, which will handle the "+" sign as well, so remove that from the format string:
>>> date_string = "Sun Jan 22 21:32:58 +0000 2012"
>>> datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
datetime.datetime(2012, 1, 22, 21, 32, 58, tzinfo=datetime.timezone.utc)
You're missing colons : and the day format string %d. See the official documentation of strptime for a table that shows the different formatting values.
from datetime import datetime
strDate = 'Mon Apr 29 14:30:53 2019'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S %Y')
You can get rid of the '+0000' like this:
from datetime import datetime
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate.replace(strDate.split(" ")[4] + " ", ""), '%a %b %d %H:%M:%S %Y')
print(objDate)
-> 2012-01-22 21:32:58
By the way,
1. The example of code that you post is not the one for the problem that you are asking about! (it does not include the +0000 in the string).
2. The error that you share (false format of the date, which has been answered already and described f.ex. here) is for another code, not the one you present above! (Error throws '%d %m %H %M %S %Y' instead of '%a %b %H %M %S %Y').
In your string u are missing the %d to catch the Day of month 01-31
'%a %b %d %H:%M:%S %Y'
If u want also to catch the +0000 u have to use the %z notation
Use this as a refrence to build your string correctly:
http://strftime.org/

convert string date to another string date

from datetime import datetime
y='Monday, December 9, 2019'
I want to convert the above string to DD/MM/YYYY I tried
c=datetime.strptime(y,'%A, %B %-d,%Y')
so I can then easily convert it but it is giving me ValueError: '-' is a bad directive in format '%A, %B %-d,%Y I checked this question
'-' is a bad directive in format '%Y-%-m-%-d' - python/django but still gives error, is there a way to do this without using re ?
The correct format is '%A, %B %d, %Y' (noticed the removed -), and to change it to DD/MM/YYYY, the format is %d-%m-%Y'
from datetime import datetime
y='Monday, December 9, 2019'
#Fixed format
c=datetime.strptime(y,'%A, %B %d, %Y')
#Changed to represent DD/MM/YYYY
print(c.strftime('%d-%m-%Y'))
The output will be
09-12-2019

How to fix ValueError: uncoverted data remains: in datetime conversion (from json) - Flask?

Trying to take date parameters in a flask app and I get hit with this error
ValueError: unconverted data remains: 0530 (India Standard Time)
The date input string is of the format:
Mon Feb 25 2019 10:31:13 GMT+0530 (India Standard Time)
The error is getting thrown in the format input of
%a %b %d %Y %X %Z
If i try another date format
%a %b %d %Y %H:%M:%S %X %Z
I get bombed with another error
error: redefinition of group name 'H' as group 8; was group 5
The string format should be "%a %b %d %Y %X %Z%z". Missing %z at the end of the string.
Edit:
I tried this way:
>>> from datetime import datetime
>>> date_str = "Mon Feb 25 2019 10:31:13 GMT+0530"
>>> datetime.strptime(date_str, "%a %b %d %Y %X %Z%z")
datetime.datetime(2019, 2, 25, 10, 31, 13, tzinfo=datetime.timezone(datetime.timedelta(0, 19800), 'GMT'))

Convert string to DateTime for mysql in python

I want to convert my date into DateTime object for MySQL.
My string format is: Mon Aug 27 04:47:45 +0000 2018
Expected Output: 'YYYY-M-D H:mm:ss'
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')
Refer section 8.1.8
here
If you are using python 3, this solution would work -
from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'
But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here
Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')
You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:
query = "select * from table where date >" + str(date_as_dt_object)
Check out this list for Python's strftime directives.
http://strftime.org/

Convert datetime in python

How do i convert this datetime using python?
2017-10-16T08:27:16+0000
I tried to use strptime but getting ValueError: time data '2017-10-16T08:27:16+0000' does not match format 'The %d %B %Y at. %H:%M'
import datetime
datetime.datetime.strptime("2017-10-16T08:27:16+0000", "The %d %B %Y at. %H:%M")
'''
I want my output to look like this
The 16 october 2017 at. 08:27
'''
First parse the string correctly, then print it in the desired format:
import datetime
date = datetime.datetime.strptime("2017-10-16T08:27:16+0000", "%Y-%m-%dT%H:%M:%S%z")
print(date.strftime("The %d %B %Y at. %H:%M"))
https://blogs.harvard.edu/rprasad/2011/09/21/python-string-to-a-datetime-object/
You have to first strip your date using strptime() and then rebuild it using strftime()
import datetime
time = "2017-10-16T08:27:16+0000"
stripedTime = datetime.datetime.strptime(time, '%Y-%m-%dT%I:%M:%S%z')
rebuildTime = stripedTime.strftime('The %d %B %Y at. %H:%M')
print(rebuildTime)

Categories

Resources