1

I have a dataframe that has two columns named created_at and updated_at which are date strings with format %Y-%m-%dT%H:%M:%S+0000. I need them to be converted to '%Y-%m-%d %H:%M:%S'. I have tried the following things but none works:

data[['created_at', 'updated_at']] = pd.to_datetime(
                data[['created_at', 'updated_at']], format='%Y-%m-%dT%H:%M:%S+0000').dt.strftime('%Y-%m-%d %H:%M:%S')

data[['created_at', 'updated_at']] = data[['created_at', 'updated_at']].apply(
                lambda x: datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S+0000').strftime('%Y-%m-%d %H:%M:%S'))

data[['created_at', 'updated_at']] = pd.to_datetime(
                data[['created_at', 'updated_at']], infer_datetime_format=True, utc=True)

How could I solve it? Thanks

4
  • are you sure you want to use a literal +0000 in the format code? this will get you into trouble in case the UTC offset changes... In general, I think you don't need a format code here at all; pandas will auto-detect ISO8601 just fine. Commented Oct 14, 2020 at 9:39
  • I don't want to use +0000. I get this time format and I have to upload it to Redshift, so nothing to do there Commented Oct 14, 2020 at 10:44
  • to clarify: from your code sample, I'd assume only your input contains a UTC offset in the form of +-xxxx. Do you want the output to have that as well? Commented Oct 14, 2020 at 10:53
  • You assumed right. In the output I just want the format '%Y-%m-%d %H:%M:%S'. jezrael answer is correct Commented Oct 14, 2020 at 13:26

1 Answer 1

2

Use:

f = lambda x: pd.to_datetime(x, utc=True).dt.strftime('%Y-%m-%d %H:%M:%S')
data[['created_at', 'updated_at']] = data[['created_at', 'updated_at']].apply(f)
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.