I want to convert type of string date to other format which as dd-mm-yyyy
date_stringg='24. Juli 2020'
date_object = datetime.strptime((date_stringg), "%d. %B %Y")
print("date_object: ", date_object)
You may need to set the locale. Juli is not a valid month name in english language, I'm assuming it is Dutch.
Assuming you want to use the Dutch locale with datetime, you can do the following
import locale
locale.setlocale(locale.LC_TIME, "nl_nl")
After that, it will recognize Juli so this will work
>>> date_stringg='24. Juli 2020'
>>>
>>> date_object = datetime.strptime((date_stringg), "%d. %B %Y")
>>> date_object
datetime.datetime(2020, 7, 24, 0, 0)
This looks like a locale setting problem. See the example below:
>>> locale.setlocale(locale.LC_ALL, 'C')
'C'
>>> datetime.datetime.strptime('24. Julho 2020', '%d. %B %Y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/local/lib/python3.8/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '24. Julho 2020' does not match format '%d. %B %Y'
>>> locale.setlocale(locale.LC_ALL, 'pt_PT.utf8')
'pt_PT.utf8'
>>> datetime.datetime.strptime('24. Julho 2020', '%d. %B %Y')
datetime.datetime(2020, 7, 24, 0, 0)
You may need to select (and maybe install/configure your underlying system) for the language you are using in the strings you want to parse.
In the example you see I wrote the string 'Julho' (July) in Portuguese, so the proper locale has to be active.
See also the Python documentation on setting the locale
Related
I'm curious why the timezone in this example, GMT, is not parsed as a valid one:
>>> from datetime import datetime
>>> import pytz
>>> b = 'Mon, 3 Oct 2016 21:24:17 GMT'
>>> fmt = '%a, %d %b %Y %H:%M:%S %Z'
>>> datetime.strptime(b, fmt).astimezone(pytz.utc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
Doing the same with a -0700 instead of GMT and %z instead of %Z in the format works just fine.
What's the proper way to parse dates ending in string time zones if not this?
Use .replace() method with datetime object to update the time zone info.
>>> datetime.strptime(b, fmt).replace(tzinfo=pytz.utc)
datetime.datetime(2016, 10, 3, 21, 24, 17, tzinfo=<UTC>)
Since you mentioned, .astimezone() is working with %Z instead of %s in the format string. Even though there is z in both the formatting (difference in just case), but they are totally different in terms of what they represent.
As per the strftime's directive document:
%z : UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).
%Z : Time zone name (empty string if the object is naive).
I have date as
In [1]: a = "Sun 10 May 2015 13:34:36 -0700"
When I try to convert it using strptime, its giving error.
In [3]: datetime.strptime(a, "%a %d %b %Y %H:%M:%S %Z"
...: )
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-973ef1c6daca> in <module>()
----> 1 datetime.strptime(a, "%a %d %b %Y %H:%M:%S %Z"
2 )
/usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format)
323 if not found:
324 raise ValueError("time data %r does not match format %r" %
--> 325 (data_string, format))
326 if len(data_string) != found.end():
327 raise ValueError("unconverted data remains: %s" %
ValueError: time data 'Sun 10 May 2015 13:34:36 -0700' does not match format '%a %d %b %Y %H:%M:%S %Z'
In [6]: datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-e4870e34edda> in <module>()
----> 1 datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
/usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format)
315 del err
316 raise ValueError("'%s' is a bad directive in format '%s'" %
--> 317 (bad_directive, format))
318 # IndexError only occurs when the format string is "%"
319 except IndexError:
ValueError: 'z' is a bad directive in format '%a %d %b %Y %H:%M:%S %z'
As per doc, correct format is %z, but I might missing some part.
From the link you provided for the python doc, I found that you are using Python 2.7
It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.
Note: from Python 3.2 onwards it will always work.
I am using Python 3.4 in which it is working fine
>>> a = "Sun 10 May 2015 13:34:36 -0700"
>>> datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
Update using dateutil
$ pip install python-dateutil
from dateutil import parser
parsed_date = parser.parse(date)
>>> parsed_date
datetime.datetime(2015, 3, 14, 18, 43, 19)
Your format string is correct and works fine in Python 3.3:
>>> a = "Sun 10 May 2015 13:34:36 -0700"
>>> datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
datetime.datetime(2015, 5, 10, 13, 34, 36, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))
It gives the error in Python 2.7 indeed.
Unlike strftime(), which is implemented by calling the libc function, strptime() is implemented in the Python library. Here you can see that the version used in Python 2.7 doesn’t support the z format. On the other hand here is the version from Python 3.3, which supports that (I think this was added around 3.2).
So, basically, you have two options:
Using some external library that is able to handle z.
Implementing it yourself (e.g. by stripping the timezone from the string, feeding the first part to strptime() and parsing the second one manually). Looking at how this is done in the Python library might be helpful.
I tried to parse this to return an “aware” object, but it is somewhat complicated.
>>> a = "Sun 10 May 2015 13:34:36 -0700"
>>> time, tz = a.rsplit(' ', 1)
>>> d = datetime.strptime(time, '%a %d %b %Y %H:%M:%S')
datetime.datetime(2015, 5, 10, 13, 34, 36)
Now I have to call d.replace(tzinfo=…tz…) to replace the timezone, but the problem is that I can’t get an instance of tzinfo because just knowing the offset from UTC is not enough to identify a timezone.
In Python 3.2 there is a special timezone class that is a subclass of tzinfo representing a “fake” timezone defined by just its offset. So there are two ways to proceed:
Backport (basically, copy and paste) the timezone class from Python 3 and use it in your parser.
Return a “naive” object:
>>> d + timedelta(hours=int(tz[1:]) * (1 if tz.startswith('-') else -1))
datetime.datetime(2015, 6, 8, 17, 34, 36)
You can parse your input format using only stdlib even in Python 2.7:
>>> from datetime import datetime
>>> from email.utils import mktime_tz, parsedate_tz
>>> mktime_tz(parsedate_tz("Sun 10 May 2015 13:34:36 -0700"))
1431290076
>>> datetime.utcfromtimestamp(_)
datetime.datetime(2015, 5, 10, 20, 34, 36)
The result is a naive datetime object that represents time in UTC.
See other solutions and the way to get an aware datetime object in Python: parsing date with timezone from an email.
I'm trying to parse the following string into a valid datetime format:
Wed, 10 Sep 2014 11:20:58 +0000
for which I use this Python code:
dtObject = datetime.strptime(e[attr], '%a, %d %b %Y %H:%M:%S %z')
Unfortunately I get an error saying:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _str
ptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
According to the strptime() docs, %z should be totally correct for UTC offset in the form +HHMM or -HHMM.
Does anybody know what I'm doing wrong here? All tips are welcome
It looks as if strptime doesn't always support %z (see this answer)
Instead of strptime, you can use dateutil.parser and it works fine:
>>> import dateutil.parser
>>> s='Wed, 10 Sep 2014 11:20:58 +0000' #UTC
>>> dateutil.parser.parse(s)
datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzutc())
>>> s='Wed, 10 Sep 2014 11:20:58 +0100' #ANOTHER TZ
>>> dateutil.parser.parse(s)
datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzoffset(None, 3600))
I am need to convert a date in below format into different format for displaying purpose. But before that I am trying to convert the date in string to time object, but not able to do so.
>>> time.strptime("Thu Mar 13 23:15:13 2014 EDT", '%a %b %d %H:%M:%S %Y %Z')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib64/python2.4/_strptime.py", line 293, in strptime
raise ValueError("time data did not match format: data=%s fmt=%s" %
ValueError: time data did not match format: data=Thu Mar 13 23:15:13 2014 EDT fmt=%a %b %d %H:%M:%S %Y %Z
Did a trial and error and it's the '%Z' causing the issue, below works fine (just %Z is removed)
>>> time.strptime("Thu Mar 13 23:15:13 2014", '%a %b %d %H:%M:%S %Y')
(2014, 3, 13, 23, 15, 13, 3, 72, -1)
Python wiki (https://docs.python.org/2/library/time.html) says timezone specifier is %Z, then what is the issue here. Please help me find.
Python version: 2.4.3
From the Python documentation. https://docs.python.org/2/library/time.html#time.strptime
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).
Which basically says that time.strptime() will only recognize timezones that are listed in time.tzname
Hope this helps
%z will only work for numeric timezone in python 3.x, here is a fix for python 2.x:
Instead of using:
datetime.strptime(t,'%Y-%m-%dT%H:%M %z')
use the timedelta to account for the timezone, like this:
from datetime import datetime,timedelta
def dt_parse(t):
ret = datetime.strptime(t[0:16],'%Y-%m-%dT%H:%M')
if t[18]=='+':
ret+=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
elif t[18]=='-':
ret-=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
return ret
I need to parse date and time. Here is what I've got:
import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
print a
But it gives me
Traceback (most recent call last):
File "/home/aaa/Documents/python_test.py", line 17, in <module>
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Apr 28 2013 23:01' does not match format '%b %d %y %H:%M'
What am I doing wrong?
%y should be %Y for a 4 digit year...
From the docs:
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
You can
import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %Y %H:%M")
print time.strftime("%d/%m/%Y",a)
with Y. It is followed by a conversion line of code, and gives result
28/04/2013
Jon's answer is of course correct, but as you noticed these things can be difficult to find.
As a general suggestion for debugging strptime problems I recommend printing out a known datetime using the format string you use for parsing:
from datetime import datetime
d = datetime(2013, 4, 28, 23, 1)
print d.strftime("%b %d %y %H:%M")
print 'Apr 28 2013 23:01'
A visual comparison of the output lines:
Apr 28 13 23:01
Apr 28 2013 23:01
quickly finds the problem and also works when your format string is correct, but you are working with a different locale (e.g. in Spanish where it would expect 'Abr' instead of 'Apr')