[英]Convert a date to a different format for an entire new column
I want to convert the date in a column in a dataframe to a different format.我想将数据框中列中的日期转换为不同的格式。 Currently, it has this format: '2019-11-20T01:04:18' .
目前,它具有以下格式: '2019-11-20T01:04:18' 。 I want it to have this format: 20-11-19 1:04 .
我希望它具有这种格式: 20-11-19 1:04 。
I think I need to develop a loop and generate a new column for the new date format.我想我需要开发一个循环并为新的日期格式生成一个新列。 So essentially, in the loop, I would refer to the initial column and then generate the variable for the new column in the format I want.
所以本质上,在循环中,我会引用初始列,然后以我想要的格式为新列生成变量。
Can someone help me out to complete this task?有人可以帮我完成这项任务吗?
The following code works for one occasion:以下代码适用于一种情况:
import datetime
d = datetime.datetime.strptime('2019-11-20T01:04:18', '%Y-%m-%dT%H:%M:%S')
print d.strftime('%d-%m-%y %H:%M')
From a previous answer in this site , this should be able to help you, comments give explanation You can read your data into pandas from csv or database or create some test data as shown below for testing.从本站点的先前答案中,这应该可以帮助您,评论给出解释您可以将数据从 csv 或数据库读入 Pandas 或创建一些测试数据,如下所示进行测试。
>>> import pandas as pd
>>> df = pd.DataFrame({'column': {0: '26/1/2016', 1: '26/1/2016'}})
>>> # First convert the column to datetime datatype
>>> df['column'] = pd.to_datetime(df.column)
>>> # Then call the datetime object format() method, set the modifiers you want here
>>> df['column'] = df['column'].dt.strftime('%Y-%m-%dT%H:%M:%S')
>>> df
column
0 2016-01-26T00:00:00
1 2016-01-26T00:00:00
NB.注意。 Check to ensure that all your columns have similar date strings
检查以确保所有列都具有相似的日期字符串
You can either achieve it like this:您可以像这样实现它:
from datetime import datetime
df['your_column'] = df['your_column'].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S').strftime('%d-%m-%y %H:%M'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.