简体   繁体   中英

How to convert string into datetime in Python

i have concatenated

date(date field)
time(float)
date_time_to(Char)

i am getting output in this format "2018-10-09 20.00" .

I need output in this format '%m/%d/%Y %H:%M:%S'

I used "obj.date_time_to = datetime.strptime(self.date_time_to, "%m/%d/%Y %H:%M:%S.%f")"

i am getting

ValueError: time data '2018-10-09 20.00' does not match format '%m/%d/%Y %H:%M:%S.%f'

You need to parse the string with the right format:

from datetime import datetime

input = "2018-10-09 20.00"
#        ^^^^^^^^^^^^^^^^-----⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
d = datetime.strptime(input, "%Y-%m-%d %H.%M")  # parse to datetime object
result = d.strftime("%m/%d/%Y %H:%M:%S")        # now convert to desired format
#⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄-^^^^^^^^^^^^^^^^^ 
'10/09/2018 20:00:00'

You can use the datetime module. Check the Python documentation.

For example:

import datetime

x = "09/10/2018"
date = datetime.datetime.strptime(date, "%d/%M/%Y") # string to datetime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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