【问题标题】:Convert timestamp to month name only仅将时间戳转换为月份名称
【发布时间】:2019-06-13 19:09:59
【问题描述】:

我想将数据框列中的每个时间戳更改为月份名称。

date =[]
month=0
for j in clean_data['created_at']:
    date.append(j)
    month = time.strftime("%b",time.gmtime(date))
print(month)

我有以下错误:

TypeError:需要一个整数(类型为 str)

我的预期输出是“一月、二月、三月等...”。例如,我希望 2019-06-13T14:22:28Z 只是 Jun

【问题讨论】:

  • 示例:我希望这个 2019-06-13T14:22:28Z 只是 Jun

标签: python pandas timestamp


【解决方案1】:

试试:

clean_data['created_at']= pd.to_datetime(clean_data['created_at'])
clean_data['created_at'].dt.month_name().str[:3]

【讨论】:

  • 感谢您的及时回复。我将如何运行一个循环来遍历整个列 clean_data['created_at'] 以转换数据帧该列中的所有时间戳?
  • 这两个命令为您提供了新的字符串。如果要替换这些值,请在第二行执行 clean_data['created_at'] = clean_data['created_at'].dt.month_name().str[:3]
  • 它可以工作,但是当我运行程序 SettingWithCopyWarning 时出现此错误:试图在 DataFrame 的切片副本上设置值。尝试改用 .loc[row_indexer,col_indexer] = value
【解决方案2】:

试试:-

import datetime

# Getting month from the string
date_ = int("2019-06-13T14:22:28Z".split("-")[1])

# Extracting month name, from the number of the month
month_ = datetime.date(2000, int(date_), 1).strftime('%b')

print(month_)

输出:-

Jun

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2016-10-04
    • 1970-01-01
    相关资源
    最近更新 更多