I have a string like 23 July 1914 and want to convert it to 23/07/1914 date format.
But my code gives error.
from datetime import datetime
datetime_object = datetime.strptime('1 June 2005','%d %m %Y')
print datetime_object
Your error is in the format you are using to strip your string. You use %m as the format specifier for month, but this expects a 0 padded integer representing the month of the year (e.g. 06 for your example). What you want to use is %B, which expects an month of the year written out fully (e.g. June in your example).
For a full explanation of the datetime format specifiers please consult the documentation, and if you have any other issues please check there first.
Here is what you should be doing:
from datetime import datetime
datetime_object = datetime.strptime('1 June 2005','%d %B %Y')
s = datetime_object.strftime("%d/%m/%y")
print(s)
Output:
>>> 01/06/05
You see your strptime requires two parameters.
strptime(string[, format])
And the string will be converted to a datetime object according to a format you specify.
There are various formats
%a - abbreviated weekday name
%A - full weekday name
%b - abbreviated month name
%B - full month name
%c - preferred date and time representation
%C - century number (the year divided by 100, range 00 to 99)
%d - day of the month (01 to 31)
%D - same as %m/%d/%y
%e - day of the month (1 to 31)
%g - like %G, but without the century
%G - 4-digit year corresponding to the ISO week number (see %V).
%h - same as %b
%H - hour, using a 24-hour clock (00 to 23)
The above are some examples. Take a look here for formats
Take a goood look at these two!
%b - abbreviated month name
%B - full month name
It should be in a similar pattern to the string you provide. Confusing take a look at these examples.
>>> datetime.strptime('1 jul 2009','%d %b %Y')
datetime.datetime(2009, 7, 1, 0, 0)
>>> datetime.strptime('1 Jul 2009','%d %b %Y')
datetime.datetime(2009, 7, 1, 0, 0)
>>> datetime.strptime('jul 21 1996','%b %d %Y')
datetime.datetime(1996, 7, 21, 0, 0)
As you can see based on the format the string is turned into a datetime object. Now take a look!
>>> datetime.strptime('1 July 2009','%d %b %Y')
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
datetime.strptime('1 July 2009','%d %b %Y')
File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data '1 July 2009' does not match format '%d %b %Y'
Why error because jun or Jun (short form) stands for %b. When you supply a June it gets confused. Now what to do? Changed the format.
>>> datetime.strptime('1 July 2009','%d %B %Y')
datetime.datetime(2009, 7, 1, 0, 0)
Simple now converting the datetime object is simple enough.
>>> s = datetime.strptime('1 July 2009','%d %B %Y')
>>> s.strftime('%d/%m/%Y')
'01/07/2009
Again the %m is the format for displaying it in months (numbers) read more about them.
The placeholder for "Month as locale’s full name." would be %B not %m:
>>> from datetime import datetime
>>> datetime_object = datetime.strptime('1 June 2005','%d %B %Y')
>>> print(datetime_object)
2005-06-01 00:00:00
>>> print(datetime_object.strftime("%d/%m/%Y"))
01/06/2005
This should work:
from datetime import datetime
print(datetime.strptime('1 June 2005', '%d %B %Y').strftime('%d/%m/%Y'))
print(datetime.strptime('23 July 1914', '%d %B %Y').strftime('%d/%m/%Y'))
For more info you can read about strftime-strptime-behavior
%d means "Day of the month as a zero-padded decimal number."
%m means "Month as a zero-padded decimal number."
Neither day or month are supplied what you tell it to expect. What you need it %B for month (only if your locale is en_US), and %-d for day.
Related
I've got a string 3:01 AM - 18 Dec 2017
I've written the following pattern strftime('%-I:%M %p - %-d %b %Y') and I can't seem to get it to work, following this
My notes:
%-I hour 12-hour clock as a decimal (no zero padding)
: separation between hour and minute
%M minute as a zero padded decimal
%p AM/PM
- space-dash-space pattern betwen time and date
%-d date of the month as a decimal (no zero padding)
%b Month abbreviated
%Y Year with century as decimal
df['tweet_date'] = pd.to_datetime(df['tweet_date'], errors='coerce').apply(lambda x: x.strftime('%I:%M %p - %d %b %Y')if not pd.isnull(x) else '')
On another dataframe with a similar column this works:
df2['created_at'] = pd.to_datetime(df2['created_at'], errors='coerce').apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')if not pd.isnull(x) else '')
df2['created_at'] = df2['created_at'].astype('datetime64[s]')`
where values before formatting look like this for example 2017-10-03T15:48:10.000Z
Your format is fine but some os's can't use the negative formatting for zero-padded units. datetime should be able to parse both padded and non-padded instances of those just fine:
from datetime import datetime as dt
z_time = '06:48 PM - 03 Jun 2021'
nz_time = '6:48 PM - 3 Jun 2021'
dt.strptime(z_time, '%I:%M %p - %d %b %Y')
[out:] datetime.datetime(2021, 6, 3, 18, 48)
dt.strptime(nz_time, '%I:%M %p - %d %b %Y')
[out:] datetime.datetime(2021, 6, 3, 18, 48)
And since you're getting strings from datetimes, you should look whether your os supports certain formatting rules. Here's one for windows.
from datetime import datetime
str="3:01 AM - 18 Dec 2017"
date=datetime.strptime(str,"%I:%M %p - %d %b %Y")
To turn your string into a time, do this:
>>> import time
>>> s = "3:01 AM - 18 Dec 2017"
>>> time.strptime(s,'%I:%M %p - %d %b %Y')
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=18, tm_hour=3, tm_min=1,
tm_sec=0, tm_wday=0, tm_yday=352, tm_isdst=-1)
No hyphens after %. The are not mentioned in the official Python documentation.
I wanted to figure out how to use strftime in a lambda function or better, using the .dt accessor after the column in my dataframe had been converted to a datetime
I couldn't figure this out so I went for the next fastest method
from datetime import datetime
formatted_dates = []
for item in df.tweet_date:
formatted_dates.append(datetime.strptime(item,"%I:%M %p - %d %b %Y"))
df.tweet_date = formatted_dates
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'))
I have a string variable named dte that prints in the following format:
Tue Feb 13 23:49:10 +0000 2018
I'm trying to convert it to a date type so that I can work out how long ago it was in days, hours, minutes etc but keep getting the following error:
ValueError: time data 'Tue Feb 13 23:49:10 +0000 2018' does not match format '%a %b %d %I:%M:%S %z %Y'
I'm using this code:
new_date = datetime.datetime.strptime(dte, "%a %b %d %I:%M:%S %z %Y")
print(new_date)
I've tried removing the colons but get the same error. I'm sure it's something very simple I'm overlooking but can't figure out what it is.
Any help appreciated.
You need %H for the hour component not %I:
In[8]:
dte="Tue Feb 13 23:49:10 +0000 2018"
new_date = dt.datetime.strptime(dte, "%a %b %d %H:%M:%S %z %Y")
new_date
Out[8]: datetime.datetime(2018, 2, 13, 23, 49, 10, tzinfo=datetime.timezone.utc)
You have 24-hour hour component, not 12-hour which is what %I is for, see the docs
I have this string
14 Mai 2014
I want to convert it to iso 8601
i read this answer and this one,
and first i try to convert string to date and then in i convert it to iso format:
test_date = datetime.strptime("14 Mai 2014", '%d %m %Y')
iso_date = test_date.isoformat()
i got this error:
ValueError: time data '14 Mai 2014' does not match format '%d %m %Y'
According to Python strftime reference %m means day of month and in your case "Mai" seems to be name of month in your current locale and you have to use this %b format. So your piece of code should looks like this:
test_date = datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()
And don't forget to set locale.
For English locale it works:
>>> from datetime import datetime
>>> test_date = datetime.strptime("14 May 2014", '%d %b %Y')
>>> print(test_date.isoformat())
2014-05-14T00:00:00
You need to use %b token instead of %m.
And for use %b token you must set a locale.
Python Documentation
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR')
test_date = datetime.datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()
The result will be '2014-05-14T00:00:00'
I have a date with this format
October 14, 2014 1:35PM PDT
I have this in my python script
import time
u_date = 'October 14, 2014 1:35PM PDT'
print time.strptime(u_date,"%b %d, %y %I:%M%p %Z")
I got this error as a result
ValueError: time data u'October 14, 2014 1:35PM PDT' does not match format '%b %d, %y %I:%M%p %Z'
Can anyone explain to me why is this happening? I'm new to python and any help will be appreciated.
Your format is incorrect; %b takes an abbreviated month, but you have a full month, requiring %B, and you have a full 4-digit year, so use %Y, not %y.
The time library cannot parse timezones, however, you'll have to drop the %Z part here and remove the last characters for this to work at all:
>>> time.strptime(u_date[:-4], "%B %d, %Y %I:%M%p")
time.struct_time(tm_year=2014, tm_mon=10, tm_mday=14, tm_hour=13, tm_min=35, tm_sec=0, tm_wday=1, tm_yday=287, tm_isdst=-1)
You could use the dateutil library instead to parse the full string, it'll produce a datetime.datetime object rather than a time struct:
>>> from dateutil import parser
>>> parser.parse(u_date)
datetime.datetime(2014, 10, 14, 13, 35)