简体   繁体   中英

How to change datetime format?

I have timestamps given in the following format in my pandas DataFrame df : 2015-03-09 11:09:05.0 . How can I transform them into this format 2015-03-09T11:09:05.0 (ie separated by T )?

df["dt"] = df["dt"].apply(lambda x: ???)

You were almost there. You are looking for the the isoformat. https://docs.python.org/3.6/library/datetime.html#datetime.date.isoformat

import pandas as pd
df = pd.DataFrame({'dt':pd.to_datetime(['2015-03-09 11:09:05.0'])})

df["dt"] = df["dt"].apply(lambda x: x.isoformat())

df

Returns

            dt
0  2015-03-09T11:09:05

You can change the T (default) by inserting a parameter to isoformat(), eg df["dt"] = df["dt"].apply(lambda x: x.isoformat(" "))

Use strftime with custom format:

df = pd.DataFrame({'dt':pd.to_datetime(['2015-03-09 11:09:05.0'])})
print (df)

df["dt"] = df["dt"].dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
print (df)
                           dt
0  2015-03-09T11:09:05.000000

Or convert to string , split by whitespace and join by T :

df["dt"] = df["dt"].astype(str).str.split().str.join('T')

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