Reputation: 261
I want to convert 2010-03-01 to 733832
I just found this toordinal code
d=datetime.date(year=2010, month=3, day=1)
d.toordinal()
from this
But i want something more like
d=datetime.date('2010-03-01')
d.toordinal()
Thanks in advance
Upvotes: 12
Views: 29613
Reputation: 48090
You need to firstly convert the time string to datetime
object using strptime()
. Then call .toordinal()
on the datetime
object
>>> from datetime import datetime
>>> date = datetime.strptime('2010-03-01', '%Y-%M-%d')
>>> date.toordinal()
733773
It is even better to create a function to achieve this as:
def convert_date_to_ordinal(date):
return datetime.strptime(date, '%Y-%M-%d').toordinal()
convert_date_to_ordinal('2010-03-01')
#returns: 733773
Upvotes: 3
Reputation: 78554
You'll need to use strptime
on the date string, specifying the format, then you can call the toordinal
method of the date
object:
>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832
The call to the date
method in this case is redundant, and is only kept for making the object consistent as a date
object instead of a datetime
object.
If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.
Upvotes: 14
Reputation: 667
like this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
Upvotes: 5