+2 votes
in Programming Languages by (11k points)
I want to convert strings like '2003-10-12' to datetime so that I can apply date comparison. How can I do?

1 Answer

+1 vote
by (14.8k points)

You need to import module datetime and then use function strptime() from that module. Here is an example:

>>> t1='2003-01-01'
>>> from datetime import datetime
>>> t2=datetime.strptime(t1, '%Y-%m-%d')
>>> t2
datetime.datetime(2003, 1, 1, 0, 0)
>>> t2.year
2003
>>> t2.month
1
>>> t2.day
1

>>> t1='2003-12-31'
>>> t3=datetime.strptime(t1, '%Y-%m-%d')
>>> t3
datetime.datetime(2003, 12, 31, 0, 0)
>>> t2
datetime.datetime(2003, 1, 1, 0, 0)
>>> t3-t2
datetime.timedelta(364)
>>> (t3-t2).days
364

Related questions

...