gpt4 book ai didi

python - 在 pandas 中应用日期时间格式进行排序

转载 作者:行者123 更新时间:2023-12-01 04:23:13 24 4
gpt4 key购买 nike

在 Pandas 中,我的日期格式为:%Y/%m/%d(例如 2015/10/31)。我想将此格式更改为其他格式,例如:%d-%m-%y(例如 31-10-15)。

将列转换为正确的对象以便稍后排序:

df['Date'] = pd.to_datetime(df['Date'])

应用 strptime:

df['Date'] = df['Date'].apply(lambda x:
datetime.strptime(x,'%d-%m-%y'))

TypeError: must be str, not Timestamp

此外,奇怪的是,如果日期以默认 ISO 标准以外的任何方式输入 pandas 数据帧,则排序时会出现奇怪的结果。例如格式不一致和/或排序不正确:

0  2015-01-31
1 2016-15-01

最佳答案

因为您已经在处理日期时间对象,所以您会收到此错误,因为 strptime 需要字符串而不是 Timestamp 对象。根据strptime的定义:

def strptime(cls, date_string, format):
'string, format -> new datetime parsed from a string (like time.strptime()).'

您实际上要做的是首先使用 strftime 将日期时间转换为您需要的字符串格式:

def strftime(self, format):
"""Return a string representing the date and time, controlled by an
explicit format string.

然后使用strptime将其返回到datetime对象。下面的demo将进行演示。请注意最后使用 .date() 来删除不需要的 00:00:00 时间部分。

>>> from datetime import datetime
>>> orig_datetime_obj = datetime.strptime("2015/10/31", '%Y/%m/%d').date()
>>> print(orig_datetime_obj)
2015-10-31
>>> print(type(orig_datetime_obj))
<type 'datetime.datetime'>
>>> new_datetime_obj = datetime.strptime(orig_datetime_obj.strftime('%d-%m-%y'), '%d-%m-%y').date()
>>> print(new_datetime_obj)
2015-10-31
>>> print(type(new_datetime_obj))
<type 'datetime.date'>

或者,如果您需要的只是将其转换为不同的格式,但以字符串形式,您可以简单地坚持仅使用 strftime 与您的新格式。使用上面的示例,您只需要这部分:

orig_datetime_obj.strftime('%d-%m-%y')

关于python - 在 pandas 中应用日期时间格式进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com