Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get datetime from date object python?

How do I get datetime from date object python?

I think of

import datetime as dt

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

Any easier solution?

like image 415
Vishal Avatar asked Dec 22 '22 06:12

Vishal


2 Answers

There are a few 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 is the most commonly used.

like image 103
Mark Byers Avatar answered Jan 02 '23 23:01

Mark Byers


Try this:

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
like image 44
Prasoon Saurav Avatar answered Jan 02 '23 23:01

Prasoon Saurav