简体   繁体   中英

How to convert current date time to a specific format

I have a date column in pandas and it has dates like this:

Fri Sep 18 2020 21:57:21 GMT+0500 (Pakistan Standard Time)

How do I convert it to a format like this :

2020-09-18 21:57:21

Let's try stripping the unnecessary text:

pd.to_datetime(df['text'].str.extract('^(.*) GMT')[0])

Output:

0   2020-09-18 21:57:21
Name: 0, dtype: datetime64[ns]

Try

print(x.strftime("%Y %b %d %H:%M:%S"))

more info here: https://stackabuse.com/how-to-format-dates-in-python/

If the format of your column is consistent, might be easier to just slice it:

df = pd.DataFrame({"time": ["Fri Sep 18 2020 21:57:21 GMT+0500 (Pakistan Standard Time)"]})

print (pd.to_datetime(df["time"].str[4:21]))

0   2020-09-18 21:57:00
Name: time, dtype: datetime64[ns]

Start by dropping the day and the last part GMT+0500 (Pakistan Standard Time).

then you could apply the function right to the column so the values are changed

df['time']=df['time'].apply(pd.to_datetime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM