【问题标题】:Timestamp to list of month and year using Python使用Python的月份和年份列表的时间戳
【发布时间】:2015-09-02 21:23:10
【问题描述】:

我想从时间戳列表中获取月份和年份的列表。

date_list 的输出是

Out[16]: 
[Timestamp('2014-09-30 00:00:00'),
 Timestamp('2014-10-31 00:00:00'),
 Timestamp('2014-11-30 00:00:00'),
 Timestamp('2014-12-31 00:00:00'),
 Timestamp('2015-01-31 00:00:00'),
 Timestamp('2015-02-28 00:00:00'),
 Timestamp('2015-03-31 00:00:00'),
 Timestamp('2015-04-30 00:00:00'),
 Timestamp('2015-05-31 00:00:00'),
 Timestamp('2015-06-30 00:00:00'),
 Timestamp('2015-07-31 00:00:00'),
 Timestamp('2015-08-31 00:00:00'),
 Timestamp('2015-09-30 00:00:00')]

我希望它是 [2014 年 9 月,2014 年 10 月,...2015 年 9 月]

如果我尝试按原样绘制它,我会得到TypeError: unsupported operand type(s) for +: 'Timestamp' and 'str',这是有道理的。我不知道如何从 Timestamp 获得情节将接受的值。我尝试使用 datetime.datetime(date_list) 并得到TypeError: an integer is required

我也尝试了pd.to_datetime(formatted.index, format='%b %Y').tolist(),但这给出了相同的时间戳输出。

编辑:有关代码的更多信息。

我的原始数据框如下所示:

groupname                             A                B     Total
recvd_dttm                                                      
2014-09-30                            21               55     76
2014-10-31                            20               66     86
2014-11-30                            18               45     63
2014-12-31                            11               46     57
2015-01-31                            25                2     27
2015-02-28                             8                1      9
2015-03-31                            29                1     30
2015-04-30                             8               66     74
2015-05-31                            10               78     88
2015-06-30                            21               59     80
2015-07-31                            14               86    100
2015-08-31                             8               90     98
2015-09-30                             2                2      4

我使用较早的数据帧df['recvd_dttm'] = pd.to_datetime(df['recvd_dttm']) 检索recv_dttm 的位置

然后我做了

total_list = formatted['Total'].values.tolist()
date_list = formatted.index.tolist()

【问题讨论】:

  • 请显示date_list 是什么。您正在显示formatted.index.tolist()Timestamp 定义在哪里?
  • @Pynchia 哎呀我打错了。 formatted.index.tolist() = date_list.显示的输出是 date_list。
  • 好的,谢谢。您对我的问题的回答仍然是片面的。 Timestamp 是什么?
  • @Pynchia 我不太确定如何回答这个问题。我输入了更多代码信息,看看是否有帮助。

标签: python pandas graph timestamp bokeh


【解决方案1】:

你可以使用时间戳自己的strftime来格式化:

[date.strftime("%b %Y") for date in date_list]

【讨论】:

  • 是的!完美,非常感谢。
  • 所以这只是一个约会,嗯?请原谅我的无知,但是Timestamp 类的打印输出来自哪里?如果我使用datetime.date.fromtimestamp(time.time()),我会得到datetime.date(2015, 9, 2)。请帮助我了解该日期是如何创建的。
  • @Pynchia 这是一个pandas Timestamp 对象(我猜到了,你说得对,它并不明显)。
  • 好的,谢谢。我还没见过熊猫呢。也许pandas 标签会有很大帮助。
  • @Pynchia: isinstance(Timestamp, datetime) == True 即,您可以使用任何带有Timestamp 对象的日期时间方法。
猜你喜欢
  • 1970-01-01
  • 2021-08-31
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 2015-05-23
相关资源
最近更新 更多