如何将日期时间转换为日期(使用Python)?


Answers

从文档:

datetime.datetime.date()

具有相同年份,月份和日期的返回日期对象。

Question

如何将datetime.datetime对象(例如, datetime.datetime.now())的返回值datetime.datetime.now())转换为Python中的datetime.date对象?




您可以使用日期时间对象的date()方法将日期时间对象转换为日期,如下所示:

<datetime_object>.date()



import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
    print datetime.datetime.fromtimestamp(dt).date()



Links