4

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?

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
Vishal
  • 18,919
  • 19
  • 75
  • 92

2 Answers2

10

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.

Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
1

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
Prasoon Saurav
  • 88,492
  • 46
  • 234
  • 343