Python: How Can I Change A Utc Timestamp From Mm/dd/yyyy Hh:mm:ss Am To Dd/mm/yyyy Hh:mm:ss Am
I cant seem to change a UTC timestamp format in python. The dates are in the following format (They are in an excel sheet) UTC EVENT TIMESTAMP 1/22/2021 8:45:28 AM 1/22/2021 8:47:5
Solution 1:
You can directly use pandas.to_datetime
on your dataframe:
>>>s = pd.Series(["1/22/2021 8:45:28 AM", "1/22/2021 8:47:52 AM"])>>>s
0 1/22/2021 8:45:28 AM
1 1/22/2021 8:47:52 AM
dtype: object
>>>t = pd.to_datetime(s, format='%m/%d/%Y %I:%M:%S %p')>>>t
0 2021-01-22 08:45:28
1 2021-01-22 08:47:52
dtype: datetime64[ns]
>>>t.dt.strftime('%d/%m/%Y %I:%M:%S %p')
0 22/01/2021 08:45:28 AM
1 22/01/2021 08:47:52 AM
dtype: object
Your problem isn't the format, it is str(col)
. To convert a column to string you call pandas.Series.astype
, if you call str
it no longer remains a Series
or df
, for example:
>>> s
01/22/20218:45:28 AM
11/22/20218:47:52 AM
dtype: object>>> str(s)
'0 1/22/2021 8:45:28 AM\n1 1/22/2021 8:47:52 AM\ndtype: object'
^ This would not work with datetime.datetime.strptime
.
Your code works for a single value:
>>>s
0 1/22/2021 8:45:28 AM
1 1/22/2021 8:47:52 AM
>>>s[0]
'1/22/2021 8:45:28 AM'
>>>datetime.strptime(s[0], '%m/%d/%Y %I:%M:%S %p')
datetime.datetime(2021, 1, 22, 8, 45, 28)
>>>datetime.strptime(s[0], '%m/%d/%Y %I:%M:%S %p').strftime('%d/%m/%Y %I:%M:%S %p')
'22/01/2021 08:45:28 AM'
If you want non leading zero-padded format, use:
# On Windows (use '%#m' instead of '%m')>>> datetime.strptime(s[0], '%m/%d/%Y %I:%M:%S %p').strftime('%d/%#m/%Y %I:%M:%S %p')
'22/1/2021 08:45:28 AM'
# On Linux (use '%-m' instead of '%m')>>> datetime.strptime(s, '%m/%d/%Y %I:%M:%S %p').strftime('%d/%-m/%Y %I:%M:%S %p')
'22/1/2021 08:45:28 AM'
Post a Comment for "Python: How Can I Change A Utc Timestamp From Mm/dd/yyyy Hh:mm:ss Am To Dd/mm/yyyy Hh:mm:ss Am"