Parsing string into datetime in Python - python

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)

Related

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

How to convert a string into date-format in python?

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.

Convert date string in excel to date object in python

I have a date in excel which is given in: dd mmm yy format i.e.,
29 Jun 18
How do I convert this string into a date object?
I get the error:
time data '13 Jul 18' does not match format '%d %m %Y'
when I try
datetime.strptime(input, '%d %m %Y')
What should the correct date format be?
Since the year in your excell is only two digits (i.e., 18 and not 2018) you need to use %y instead of %Y in your format string:
datetime.strptime(input, '%d %b %y')
For example:
datetime.strptime( '13 Jul 18', '%d %b %y')
Results with:
datetime.datetime(2018, 7, 13, 0, 0)
See this page for more information about date/time string format.
You can use python datetime module or you can use dateutil parser to parse the string date to valid datetime object. I'd go with dateutil parser as I don't have to define string format. Here is an example
from dateutil.parser import parse
dt = parse("Thu Sep 25 10:36:28 BRST 2003")
Remember to install dateutil by pip install python-dateutil
You would have to import datetime and import xlrd
Use xlrd to open the excel workbook as
book = xlrd.open_workbook("Excel.xlsx")
sheet = book.sheet_by_name("Worksheet")
Use this to convert
obj = datetime.datetime(*xlrd.xldate_as_tuple(sheet.cell(row,column).value, book.datemode))
from datetime import datetime
datetime.strptime("29 Jun 18", "%d %b %y").date()
Here you get a datetime.date object, I don't know if that's good enough for you. I recommend you to visit the documentation on the module
You can make use of strptime which follows the pattern:
datetime.strptime(date_string, format)
example:
from datetime import datetime
dt = datetime.strptime('19 Jul 2017', '%d %b %y')
Hope this helps :)
Your format is incorrect: %b is Locale's short month and %y is two digit year
import time
time.strptime('13 Jul 18', '%d %b %y')
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=13, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=194, tm_isdst=-1)

Date Format incorrect using strptime [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python strptime() and timezones?
'Saturday, December 22, 2012 1:22:24 PM EST' does not match format '%A, %B %d, %Y %I:%M:%S %p %Z'
Maybe I'm missing something but can anyone spot why this doesn't validate properly?
The strptime() function cannot handle %Z timezone parsing very well. Only UTC and GMT are really supported, and the current value of time.tzname. See the strptime documenation:
Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).
Removing the EST part of your input and the %Z part of your format string makes things work:
>>> import time
>>> time.strptime('Saturday, December 22, 2012 1:22:24 PM EST', '%A, %B %d, %Y %I:%M:%S %p %Z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Saturday, December 22, 2012 1:22:24 PM EST' does not match format '%A, %B %d, %Y %I:%M:%S %p %Z'
>>> time.strptime('Saturday, December 22, 2012 1:22:24 PM', '%A, %B %d, %Y %I:%M:%S %p')
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=22, tm_hour=13, tm_min=22, tm_sec=24, tm_wday=5, tm_yday=357, tm_isdst=-1)
or replacing the timezone EST with GMT:
>>> time.strptime('Saturday, December 22, 2012 1:22:24 PM GMT', '%A, %B %d, %Y %I:%M:%S %p %Z')
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=22, tm_hour=13, tm_min=22, tm_sec=24, tm_wday=5, tm_yday=357, tm_isdst=0)
To parse strings with a timezone other than time.tzname, GMT or UTC, use a different date parsing library. The dateutil library has an excellent parse function that handles timezones properly:
>>> from dateutil.parser import parse
>>> parse('Saturday, December 22, 2012 1:22:24 PM EST', tzinfos={'EST': -18000})
datetime.datetime(2012, 12, 22, 13, 22, 24, tzinfo=tzoffset(u'EST', -18000))
When using dateutil.parser.parse() you do have to provide your own timezone offsets for your format though.
You can save yourself a lot of trouble and use dateutil.
In [1]: from dateutil import parser
In [2]: parser.parse('Saturday, December 22, 2012 1:22:24 PM EST')
Out[2]: datetime.datetime(2012, 12, 22, 13, 22, 24)
As for the ambiguity pointed out by eumiro, you could add a tzinfo argument:
In [3]: parser.parse('Saturday, December 22, 2012 1:22:24 PM EST',tzinfos={'EST':-5*3600})
Out[3]: datetime.datetime(2012, 12, 22, 13, 22, 24, tzinfo=tzoffset('EST', -18000))
As #root suggested dateutil.parser is the robust way to parse date, but just to clarify about the issue here
I just saw the code in _strptime.py and it seems the supported time zones are
["utc", "gmt", time.tzname[0].lower()]
and in case, the current locale timezone supports daylight saving, it would append
time.tzname[0].lower() to the above list.
So when using strptime, ensure that the timezone on which you are parsing the date supports the source timezone
Here is the code for reference
def __calc_timezone(self):
# Set self.timezone by using time.tzname.
# Do not worry about possibility of time.tzname[0] == timetzname[1]
# and time.daylight; handle that in strptime .
try:
time.tzset()
except AttributeError:
pass
no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
if time.daylight:
has_saving = frozenset([time.tzname[1].lower()])
else:
has_saving = frozenset()
self.timezone = (no_saving, has_saving)
Most likely your locale timezone is empty, e.g. %Z evaluates to ''
You can test this by:
>>> fmt = '%A, %B %d, %Y %I:%M:%S %p %Z'
>>> datetime.strptime(datetime.strftime(datetime.now(), fmt), fmt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Friday, December 28, 2012 11:34:35 AM ' does not match format '%A, %B %d, %Y %I:%M:%S %p %Z'

Categories

Resources