Skip to content Skip to sidebar Skip to footer

Convert Datetime To Ordinal In Python Fails

i been had worked with dates. I want to convert datetimes to ordinal but my script fails. from datetime import datetime date = '2016/12/07 17:45' date_strip = datetime.strptime(da

Solution 1:

Because ordinal stores just the date. the ordinal cannot contain the time:

the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d.

If you want to convert to/from timestamps instead of ordinals, try this so answer.

Solution 2:

datetime.date() returns date object with same year, month and day, but not the hour, minute and second, i.e day resolution. It can be easily seen below.

>>>from datetime import datetime>>>s = "2016/12/07 17:45">>>d = datetime.strptime(s, '%Y/%m/%d %H:%M').date()>>>type(d)
<type 'datetime.date'>

Notice that datetime.toordinal is the same as self.date().toordinal().

>>>from datetime import datetime>>>dt = datetime.strptime('2016/12/07 17:45', '%Y/%m/%d %H:%M')>>>dt.toordinal() == dt.date().toordinal()
True

Post a Comment for "Convert Datetime To Ordinal In Python Fails"