1

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 (i.e. separated by T)?

df["dt"] = df["dt"].apply(lambda x: ???)
2
  • I dont see difference... Commented Oct 16, 2017 at 12:07
  • @jezrael: Sorry, I updated. Commented Oct 16, 2017 at 12:08

2 Answers 2

3

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(), e.g. df["dt"] = df["dt"].apply(lambda x: x.isoformat(" "))

Sign up to request clarification or add additional context in comments.

1 Comment

Really nice, I dont know it ;)
1

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.