0

I have a DataFrame with a str column of dates like

'time': '2018-02-25T08:00:00.000Z'

but when applying pd.to_datetime to that column, the output looks like

'time': '2018-02-25 08:00:00+00:00'

Why is the format changing? I tried

pd.to_datetime(utc = True)

and

pd.to_datetime(..., format='%Y-%m-%dT%H:%M:%S.%f%z')

but none of them seem to work and the format gets changed.

Taco22
  • 123
  • 10
  • 1
    Because it's a `datetime` and not a string? I don't understand the problem – roganjosh Jan 18 '23 at 21:41
  • @roganjosh I want to keep the format and just transform it from str to datetime. Or at least, be able to transform it back from the datetime to the original format as a string, but can't make it work either. – Taco22 Jan 18 '23 at 21:44
  • 1
    Your question doesn't make sense and I suspect you're missing something. `'2018-02-25T08:00:00.000Z'` is a _string_. What you _get back from_ `pd.to_datetime()` is a `datetime` and the formatting is irrelevant because it's not a string anymore, it has a different representation. If you want to display it back in the same format then you need `.dt.strftime()` on the column – roganjosh Jan 18 '23 at 21:47

1 Answers1

1

Following @roganjosh comments, I converted it back to string with

df['time'].dt.strftime('%Y-%m-%dT%H:%M:%S.000Z')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Taco22
  • 123
  • 10
  • It was already in that format, so why bother converting it to datetime just to convert it back? data validation? – wjandrea Jan 18 '23 at 22:04