Nankatsu
Nankatsu

Reputation: 55

Change datetime format to hours only in Pandas

I have a list of strings date. Formatted in like

Fri Apr 23 12:38:07 +0000 2021

How can I change its format? I want to take only the hours. I checked other source before, but you need to change the date format, which obviously I'm struggling rn

As I know, you can write the code like

ds['waktu'] =  pd.to_datetime(ds['tanggal'], format='%A %b %d %H:%M:%S %z %Y')

to change its format. But idk what +0000 means.

Upvotes: 0

Views: 1511

Answers (1)

SeaBean
SeaBean

Reputation: 23237

If you only want to take the hours from the date strings, you can use .dt.strftime() after the pd.to_datetime() call, as follows:

ds['waktu'] = pd.to_datetime(ds['tanggal'], format='%a %b %d %H:%M:%S %z %Y').dt.strftime('%H:%M:%S')

Note that your format string for pd.to_datetime() is not correct and need to replace %A by %a.

+0000 is the time zone, which you can parse with %z in the format string.

Demo

ds = pd.DataFrame({'tanggal': ['Fri Apr 23 12:38:07 +0000 2021', 'Thu Apr 22 11:28:17 +0000 2021']})

ds['waktu'] = pd.to_datetime(ds['tanggal'], format='%a %b %d %H:%M:%S %z %Y').dt.strftime('%H:%M:%S')

print(ds)


                          tanggal     waktu
0  Fri Apr 23 12:38:07 +0000 2021  12:38:07
1  Thu Apr 22 11:28:17 +0000 2021  11:28:17

Upvotes: 2

Related Questions