日期1:20061201
日期2:?!01/12/2006将数字转换成一个特殊的日期时间
如何使用大熊猫在Python DATE1转换成日期2(日/月/年)格式感谢日期1和Date2是csv文件中的两列。
日期1:20061201
日期2:?!01/12/2006将数字转换成一个特殊的日期时间
如何使用大熊猫在Python DATE1转换成日期2(日/月/年)格式感谢日期1和Date2是csv文件中的两列。
数据:
In [151]: df
Out[151]:
Date
0 20061201
1 20170530
选项1:
In [152]: pd.to_datetime(df.Date, format='%Y%m%d').dt.strftime('%d/%m/%Y')
Out[152]:
0 01/12/2006
1 30/05/2017
Name: Date, dtype: object
选项2:
In [153]: df.Date.astype(str).str.replace('(\d{4})(\d{2})(\d{2})', r'\3/\2/\1')
Out[153]:
0 01/12/2006
1 30/05/2017
Name: Date, dtype: object
最简单的方法可能是使用datetime提供的日期解析:
from datetime import datetime
datetime.strptime(str(20061201), "%Y%m%d")
你可以在你的熊猫数据帧/系列使用应用这一转变过程中的所有行如下:
from datetime import datetime
def convert_date(d):
return datetime.strptime(str(d), "%Y%m%d")
df['Date2'] = df.Date1.apply(convert_date)
这将向您的数据框df
添加一个Date2
列,这是Date1
列的日期时间表示。
然后,您可以通过使用strftime
再次连载日期:
def reformat_date(d):
year = d // 10000
month = d % 10000 // 100
day = d % 100
return "{day}/{month}/{year}".format(day=day, month=month, year=year)
df['Date2'] = df.Date1.apply(reformat_date)
这比使用解析装置相当快一点:
def serialize_date(d):
return d.strftime(d, "%d/%m/%Y")
df['Date2'] = df.Date2.apply(serialize_date)
或者你可以用字符串操作做这一切由strptime
提供。
一个注意:如果工作在真正的大数据集,strptime有点慢(因为它做了很多额外处理)。 – TemporalWolf
日期时间默认显示:年/月/日。但我需要日/月/年输出格式。谢谢! – andrew
将序列化添加到所需的格式和字符串操作版本。 – cdecker
import datetime
A=datetime.datetime.strptime('20061201','%Y%m%d')
A.strftime('%m/%d/%Y')
如果您使用pandas
并希望timestamp
对象返回
pd.to_datetime('20061201')
Timestamp('2006-12-01 00:00:00')
如果你想有一个字符串返回
str(pd.to_datetime('20061201').date())
'2006-12-01'
假设你有一个数据帧df
df = pd.DataFrame(dict(Date1=['20161201']))
然后,您可以使用矢量化形式的相同技术。
为时间戳
df.assign(Date2=pd.to_datetime(df.Date1))
Date1 Date2
0 20161201 2016-12-01
为字符串
df.assign(Date2=pd.to_datetime(df.Date1).dt.date.astype(str))
Date1 Date2
0 20161201 2016-12-01
您可以使用申请,并在这里lambda函数。
假设你有一个数据集如下命名df
:
id date1
0 20061201
2 20061202
您可以使用类似的代码如下:
df['date2'] = df['date1'].apply(lambda x: x[6:] + '/' + x[4:6] + '/' + x[:4])
结果将是:
id date1 date2
0 20061201 01/12/2016
2 20061202 02/12/2016
我喜欢option2谢谢! – andrew
@andrew,欢迎您!请考虑[接受](http://meta.stackexchange.com/a/5235)最有用的答案,并提出所有有用的答案。 – MaxU