Reputation: 161
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(date, '%Y/%m/%d %H:%M').date()
ordinal = date_strip.toordinal()
# ordinal = 736305
normal_date = datetime.fromordinal(ordinal)
# normal_date = 2016-12-07 00:00:00 not 2016-12-07 17:45:00
whats wrong? ca they help me please?
Upvotes: 1
Views: 3480
Reputation: 18027
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
Upvotes: 0
Reputation: 7952
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.
Upvotes: 1