我已经研究了如何执行此操作,但是当我分别打印日期和时间时,还会出现其他值,例如00:00:00
和1900-01-01
。
代码:
import datetime
date = datetime.datetime.strptime('17/12/2018', '%d/%m/%Y')
time = datetime.datetime.strptime('13:26:09', '%H:%M:%S')
print(date)
print(time)
预期输出:
17/12/2018
13:26:09
>>>
输出:
2018-12-17 00:00:00
1900-01-01 13:26:09
>>>
答案 0 :(得分:1)
您可以简单地使用datetime.date()
和datetime.time()
函数:
import datetime
date = datetime.datetime.strptime('17/12/2018', '%d/%m/%Y') # this is a datetime
time = datetime.datetime.strptime('13:26:09', '%H:%M:%S') # this is also a datetime
print(date.date()) # just the date
print(time.time()) # just the time
输出:
2018-12-17 # do date.strftime('%%d/%m/%Y') to create the string representation you want
13:26:09 # default visualisation is same as you want
您创建2个datetime实例-一个只能通过指定时间,另一个可以只购买指定日期。默认情况下提供其他参数。
或者,您可以使用:
date = datetime.datetime.strptime('17/12/2018', '%d/%m/%Y').date() # date object
time = datetime.datetime.strptime('13:26:09', '%H:%M:%S').time() # time object