简体   繁体   English

如何将当前日期时间转换为特定格式

[英]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/更多信息: 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).首先删除一天和最后一部分 GMT+0500(巴基斯坦标准时间)。

then you could apply the function right to the column so the values are changed然后您可以将函数正确应用于该列,以便更改值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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