1

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?

Samael Olascoaga
  • 161
  • 2
  • 10

2 Answers2

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.

Community
  • 1
  • 1
TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
0

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
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134