问题:如何将日期时间转换为日期(在Python中)?
如何转换datetime.datetime
对象(例如,datetime.datetime.now())
到datetime.date
Python中的对象?
How do I convert a datetime.datetime
object (e.g., the return value of datetime.datetime.now())
to a datetime.date
object in Python?
回答 0
使用date()
方法:
datetime.datetime.now().date()
Use the date()
method:
datetime.datetime.now().date()
回答 1
回答 2
您使用的datetime.datetime.date()
方法:
datetime.datetime.now().date()
显然,以上表达式可以(并且应该恕我直言:)写成:
datetime.date.today()
You use the datetime.datetime.date()
method:
datetime.datetime.now().date()
Obviously, the expression above can (and should IMHO :) be written as:
datetime.date.today()
回答 3
您可以使用日期时间对象的date()方法将datetime对象转换为日期,如下所示:
<datetime_object>.date()
You can convert a datetime object to a date with the date() method of the date time object, as follows:
<datetime_object>.date()
回答 4
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()
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()
回答 5
您可以输入以下代码形式((今天的日期和日期和时间的名称):
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
’19 -09-09 Mon 17:37:56′
并输入以下代码(仅用于今天):“
datetime.date.today().strftime('%y-%m-%d')
19-09-10”
对于对象:
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()
you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
’19-09-09 Mon 17:37:56′
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
’19-09-10′
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()