Python date string to date object
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping
--
Chapters
00:00 Question
00:32 Accepted answer (Score 750)
00:48 Answer 2 (Score 102)
00:58 Answer 3 (Score 81)
01:49 Answer 4 (Score 46)
02:15 Thank you
--
Full question
https://stackoverflow.com/questions/2803...
Accepted answer links:
[strptime]: http://docs.python.org/library/datetime....
[datetime]: http://docs.python.org/library/datetime....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #date
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping
--
Chapters
00:00 Question
00:32 Accepted answer (Score 750)
00:48 Answer 2 (Score 102)
00:58 Answer 3 (Score 81)
01:49 Answer 4 (Score 46)
02:15 Thank you
--
Full question
https://stackoverflow.com/questions/2803...
Accepted answer links:
[strptime]: http://docs.python.org/library/datetime....
[datetime]: http://docs.python.org/library/datetime....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #date
#avk47
ACCEPTED ANSWER
Score 806
You can use strptime in the datetime package of Python:
>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)
ANSWER 2
Score 111
import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()
ANSWER 3
Score 86
Directly related question:
What if you have
datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()
and you get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
format_regex = _TimeRE_cache.compile(format)
File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
return re_compile(self.pattern(format), IGNORECASE)
File "/usr/local/lib/python2.7/re.py", line 194, in compile
return _compile(pattern, flags)
File "/usr/local/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4
and you tried:
<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()
but you still get the traceback above.
Answer:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))
ANSWER 4
Score 12
you have a date string like this, "24052010" and you want date object for this,
from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()
this cus_date will give you date object.
you can retrieve date string from your date object using this,
cus_date.strftime("%d%m%Y")