如何从日期对象python获取日期时间?
我想到了
import datetime as dt
today = dt.date.today()
date_time = dt.datetime(today.year, today.month, today.day)
更简单的解决方案?
答案 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