如何将datetime转换为date(在python中)?

How do I convert datetime to date (in Python)?

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


使用方法:date()

1
datetime.datetime.now().date()


从文档:

datetime.datetime.date()

Return date object with same year, month and day.


使用方法:你datetime.datetime.date()

1
datetime.datetime.now().date()

显然,以上的CAN(恕我直言和要表达的是:写:)

1
datetime.date.today()


你可以转换为DateTime对象A到一个约会的日期(日期时间)方法作为对象,如下:

1
<datetime_object>.date()

不要忘记要导入的DateTime

1
2
import datetime
dt=str(datetime.datetime.now().date())

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()