0

We have converted the format from UTC to Europe/Berlin, but time is unchanged. We're using python and pandas on an ubuntu server.

We have tried to run a code that supposedly should change time as well as the format. Nonetheless, time is the same.

import pandas as pd 

df = pd.read_csv('feeds.csv', date_parser=dateparse)

df['created_at'] = df['created_at'].str.replace(' UTC', '')
df['created_at'] = pd.to_datetime(df['created_at'])
df['created_at'].dt.tz_localize('UTC').dt.tz_convert('Europe/Berlin').dt.strftime('%Y-%m-%d %H:%M:%S')

df.to_csv('feeds.csv',index=False)


print(df)

Time should be changed, so that 12:50:13 changes to 14:50:13

enter image description here

4
  • 2
    assign it back df['created_at']=df['created_at'].dt.tz_localize('UTC').dt.tz_convert('Europe/Berlin').dt.strftime('%Y-%m-%d %H:%M:%S') Commented Aug 1, 2019 at 14:12
  • Please don't post images of code/data/Tracebacks. Just copy the text, paste it in your question and format it as code. You should not post code as an image because: Commented Aug 1, 2019 at 14:24
  • 2
    Also see How to make good reproducible pandas examples for very good advice on how to post Pandas questions. We don't need the CSV input, we just need a small dataframe. I created a minimal example in my answer. Commented Aug 1, 2019 at 14:25
  • Thanks, but due to time, you have to wait 10 min, @wwii :-) Commented Aug 1, 2019 at 14:30

1 Answer 1

1

You need to assign the result of your conversion back to the column:

df['created_at'] = df['created_at'].dt.tz_localize('UTC').dt.tz_convert('Europe/Berlin').dt.strftime('%Y-%m-%d %H:%M:%S')

You already did so on the preceding two lines.

You can skip the dt.tz_localize() call by telling pd.to_datetime() to handle this for you:

df['created_at'] = pd.to_datetime(df['created_at'], utc=True)
df['created_at'] = df['created_at'].dt.tz_convert('Europe/Berlin').dt.strftime('%Y-%m-%d %H:%M:%S')

Finally, just chain all operations into one:

df['created_at'] = (
    pd.to_datetime(df['created_at'].str.replace(' UTC', ''), utc=True)
    .dt.tz_convert('Europe/Berlin')
    .dt.strftime('%Y-%m-%d %H:%M:%S')
)

Demo:

>>> import pandas as pd
>>> df = pd.DataFrame({"created_at": ["2019-07-26 12:50:13 UTC", "2019-07-26 13:00:13 UTC"]})
>>> df
                created_at
0  2019-07-26 12:50:13 UTC
1  2019-07-26 13:00:13 UTC
>>> df['created_at'] = (
...     pd.to_datetime(df['created_at'].str.replace(' UTC', ''), utc=True)
...     .dt.tz_convert('Europe/Berlin')
...     .dt.strftime('%Y-%m-%d %H:%M:%S')
... )
>>> df
            created_at
0  2019-07-26 14:50:13
1  2019-07-26 15:00:13
Sign up to request clarification or add additional context in comments.

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.