简体   繁体   中英

Python Convert Integers to YYYY-MM-DD HH:MM:SS Format

I need to convert a df with a data column of integers and convert this to the following format in the current year: YYYY-MM-DD HH:MM:SS. I have a DF that looks like this:

       Date   LT Mean
0     7  5.491916
1     8  5.596823
2     9  5.793934
3    10  7.501096
4    11  8.152358
5    12  8.426322

And, I need it to look like this using the current year 2020:

   Date   LT Mean
0     2020-07-01  5.491916
1     2020-08-01  5.596823
2     2020-09-01  5.793934
3     2020-10-01  7.501096
4     2020-11-01  8.152358
5     2020-12-01  8.426322

I have not been able to find a reference for converting a single integer used for the date and converting it into the yyyy-mm-dd hh:mm:ss format i need. Thank you,

You can use pandas to_datetime function. Assuming your Date column represents the month, you can use like this:

df['Date'] = pandas.to_datetime(df["Date"], format='%m').apply(lambda dt: dt.replace(year=2020))

Then if you need transform the column to string in the specified format:

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d %H:%m:%s')

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