我有一个数据集,其中包含"DD/MM/YYYY“格式的日期列。
我只能按年进行切片和排序,但我无法对其进行切片,因为此日期列具有数据类型"object“。
请给我建议一下我要做什么。
发布于 2018-12-26 22:30:18
您的最佳选择是datetime.datetime.strptime()
函数:
由于您有一个datetime.datetime对象,所以可以使用.year属性对have进行扩展:
日期时间代码解释:
# Import Datetime from Datetime Package :
from datetime import datetime
# Initialise the String Value :
string = "2018-27-12 19:21:10"
# Using strptime method from datetime
# Convert the String to Date in '%Y-%m-%d %H:%M:%S' Format :
# Note : %m denotes 'Month' and %M denotes 'Minute' :
date_time = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
# Extract the Year using .year Attribute :
print(date_time.year)
产出:
2018
编辑:这也可以使用pandas.to_datetime方法实现
https://stackoverflow.com/questions/52726072
复制相似问题