python - 值错误: time data '2018 May 23' does not match format '%Y%b%d' (match)

标签 python pandas datetime

我知道这个问题已经被问过很多次并且有很多答案。我遵循了之前的线程,但仍然遇到错误。我正在尝试将日期列表转换为将日期定义为一年中的第 n 个日期的格式。

我在 pandas 数据框中有一个时间列表,我将其定义为:

time = data.loc[:, 'date']

例如,这会以“2018 年 9 月 12 日”的形式打印日期。我正在尝试将这些日期转换为一年中的第 n 天,从今天开始回溯。所以我希望这些日期类似于“5 天前”、“10 天前”等。

当我尝试使用 pandas datetime 模块时,我收到一个值错误,该错误甚至无法识别格式,我不确定为什么。我有:

date = pd.to_datetime(time, format='%Y%b%d')

但我收到了 ValueError:

ValueError:时间数据“2018 年 5 月 23 日”与格式“%Y%b%d”不匹配(匹配)

我计划遵循以下路线:

new_year_day = pd.Timestamp(year=date.year, month=1, day=1)
day_of_the_year = (date - new_year_day).days + 1

虽然我不确定这会得到我想要的东西。

有谁知道 1) 为什么我收到 ValueError,2) 如何修复,3) 如何将日期格式设置为“x 天前”?

感谢您的任何意见。

最佳答案

如果将整个“日期”列转换为日期时间戳,您可以获得另一列,即今天与日期(以天为单位)之间的差异

import datetime
today = datetime.datetime.now()
df['date']= pd.to_datetime(df['date'],format='%Y %b %d')
def delta(x):
   dif = today-x
   res=dif.days
   return res
df['days_diff'] = df['date'].apply(delta)

如果你愿意,那么你可以将df['days_diff']作为一个列表,并在打印它们时逐一添加文本“days ago”。

或者,如果过去的天数和日期中的“天数”为 future 就在专栏本身。但是,这会将 df['days_diff'] 的类型从“int”转换为“object”。

df['days_diff'] = np.where(df['days_diff']>=0, df['days_diff'].astype(str)+ 'days ago',df['days_diff'].astype(str)+ 'days to go')

关于python - 值错误: time data '2018 May 23' does not match format '%Y%b%d' (match),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57211533/

相关文章:

python - 使用python同时下载文件并插入到mysql数据库

python - 如何从列表中每行显示 5 个数字?

python - 在 pandas 的 groupby 中滚动应用函数

python - 过滤 pandas 中的数据框

c# - 在执行 ISQLQuery.UniqueResult<DateTime>() 时,如何让 SQLite 返回正确的 DateTime?

java - 使用 with* 函数、TemporalAdjusters 或设置 TemporalFields 调整 ZonedDateTimes 之间有什么区别吗?

python - 在 pandas 列表列中添加特定列表元素

python - Django应用程序布局: Internationalization

python - 为第一行中的多列插入 0 的逻辑 - Pandas

mysql - rails : how to find all users older then n minutes ago where n is stored in joined group