简体   繁体   中英

How to enforce datetime format (%Y-%m-%d %H:%M:%S) when the time is 00:00:00 when using pandas to_datetime() function?

I have to save one record of a dataframe with a datetime column to a csv.The datetime column is in this %Y-%m-%d %H:%M:%S format.When the record has the following value in the date column eg: 2019-11-12 00:00:00 ,the value is saved as ' 2019-11-12 '.Is there a way to enforce the datetime format?

pandas version: 0.24.2

#eg 
d = {'run_date': ['2019-11-11 02:30:00','2019-11-12 00:00:00'], 'value': [40, 45]}

df = pd.DataFrame(data=d)
display(pd.to_datetime(df['run_date'],format='%Y-%m-%d %H:%M:%S')[-1:])

You can also specify the datetime format while saving to csv.

Please try df.iloc[-1:].to_csv("test_datetime_format.csv", index=False, date_format='%Y-%m-%d %H:%M:%S') and see if that works.

I've added .iloc[-1] to select the record you had issues with, but it should also work on the complete dataframe if you wish.

Regards, Koen

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