如何从日期对象python获取日期时间?

时间:2010-01-01 13:34:40

标签: python datetime

如何从日期对象python获取日期时间?

我想到了

import datetime as dt

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

更简单的解决方案?

2 个答案:

答案 0 :(得分:9)

有几种方法可以做到这一点:

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

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

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

我认为第一种是最常用的。

答案 1 :(得分:1)

试试这个:

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)

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