简体   繁体   中英

How to convert a string to a particular date format in Python

I am reading a csv into a dataframe and trying to format data from a date column. The value for that column is showing as: "2/1/2021 0:00:00" as a class 'str'. I want to convert it to an actual datetime type formatted like this:

 date_obj1 = datetime.datetime.strptime(p_date, "%Y-%m-%dT%H:%M:%S")

but I am getting an error saying ValueError: time data '2/1/2021 0:00:00' does not match format '%Y-%m-%dT%H:%M:%S' What am I doing wrong here?

Any character not preceded by a % symbol in your format string means that it will be matched as-is. In your current format string, these characters are - , T and : . For instance, your current format string of %Y-%m-%dT%H:%M:%S successfully imports 2021-02-01T00:00:00 as a datetime object.

A format string that works with your specified data format is %m/%d/%Y %H:%M:%S .

See thedocumentation for more information.

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