简体   繁体   English

如何将字符串转换为日期/时间?

[英]How to convert string into date/time?

I have researched how to do this, but when I print the date and time separately there are other values that appear eg 00:00:00 and 1900-01-01 . 我已经研究了如何执行此操作,但是当我分别打印日期和时间时,还会出现其他值,例如00:00:001900-01-01

Code: 码:

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)

Expected Output: 预期产量:

17/12/2018
13:26:09
>>>

Output: 输出:

2018-12-17 00:00:00
1900-01-01 13:26:09
>>>

You can simply use the datetime.date() and datetime.time() functions: 您可以简单地使用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

Output: 输出:

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

You create 2 datetime instances - one only by specifying the time, the other buy only specifying the date. 您创建2个datetime实例-一个只能通过指定时间,另一个只能通过指定日期来购买。 The other param is supplied by default. 默认情况下提供其他参数。


Alternativly you can use: 或者,您可以使用:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM