How to get datetime from python date object?

How to get datetime from python date object?

I think about

import datetime as dt

today = dt.date.today()
date_time = dt.datetime(today.year, today.month, today.day)

Any simpler solutions?

+3
source share
2 answers

There are several ways to do this:

mydatetime = datetime.datetime(d.year, d.month, d.day)

or

mydatetime = datetime.combine(d, datetime.time())

or

mydatetime = datetime.datetime.fromordinal(d.toordinal())

I think the first one is most commonly used.

+9
source

Try the following:

import datetime

print 'Now    :', datetime.datetime.now()
print 'Today  :', datetime.datetime.today()
print 'UTC Now:', datetime.datetime.utcnow()

d = datetime.datetime.now()
for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
   print attr, ':', getattr(d, attr)

or

mdt = datetime.datetime(d.year, d.month, d.day) #generalized
+1
source

Source: https://habr.com/ru/post/1727029/


All Articles