将数字转换为日期

时间:2015-06-30 19:56:27

标签: python matplotlib

我想将数组中的数字(int)转换为日期格式,并将其绘制在matplotlib中。

我的问题是,有些年份与他们有几个月,而有些年份没有。 我在年和年+月拆分数组。 现在我被卡住了,希望有人可以提供帮助。

listyear = ['1967', '1968', '1969', '1970', '1971', '1972', '1973', 
'1974', '1975', '1976', '1977', '1978', '1979', '1980', '1981', '1982', 
'1983', '1984', '1985', '1986', '1987', '1988', '1989', '1990', '1991', 
'1992', '1993', '1994', '1995', '1996', '1997', '1998', '1999', '2000', 
'2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', 
'2010', '2011', '2012']

listyearandmonth = ['01.2013', '11.2013', '03.2014', '12.2014']

1 个答案:

答案 0 :(得分:0)

由于您没有提及任何与日期相关的数据,我所做的就是将给定年份从两个列表转换为datetime.dateMatplotlib's date API中提到的date demo个对象:

#!/usr/bin/env python3
# coding: utf-8

import datetime

listyear = ['1967', '1968', '1969', '1970', '1971', '1972', '1973', 
'1974', '1975', '1976', '1977', '1978', '1979', '1980', '1981', '1982', 
'1983', '1984', '1985', '1986', '1987', '1988', '1989', '1990', '1991', 
'1992', '1993', '1994', '1995', '1996', '1997', '1998', '1999', '2000', 
'2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', 
'2010', '2011', '2012']

listyearandmonth = ['01.2013', '11.2013', '03.2014', '12.2014']

# Extract years from the given list and extend those to list `listyear`
# Assumption: Dates given in list `listyearandmonth` have the format <MM.YYYY>
listyear.extend([y[1] for y in [s.split('.') for s in listyearandmonth]])

# Convert years given in list `listyear` to `datetime.date` objects
# Assumption: Do not care about month and day (set both to 1)
datetime_yrs = [datetime.date(int(y), 1, 1) for y in listyear]
相关问题