Python 将数字转换为日期

Python 将数字转换为日期,python,matplotlib,Python,Matplotlib,我想将数组中的数字(int)转换为日期格式,以便在matplotlib中打印 我的问题是有些年份有几个月和他们在一起,而有些年份没有。 我将数组分为年和年+月。 现在我陷入困境,希望有人能帮助我 listyear = ['1967', '1968', '1969', '1970', '1971', '1972', '1973', '1974', '1975', '1976', '1977', '1978', '1979', '1980', '1981', '1982', '1983', '1

我想将数组中的数字(
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']

由于您没有提到任何与日期相关的数据,我所做的只是将两个列表中的给定年份转换为或中提到的对象:

#/usr/bin/env蟒蛇3
#编码:utf-8
导入日期时间
列表年份=['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']
列表年份和月份=['01.2013','11.2013','03.2014','12.2014']
#从给定列表中提取年份,并将这些年份扩展到列表“listyear”`
#假设:列表“listyearandmonth”中给出的日期具有以下格式
listyear.extend([y[1]表示listyear和Month]]中的[s.split('.')表示s中的y)
#将列表'listyear'中给定的年份转换为'datetime.date'对象
#假设:不关心月份和日期(均设置为1)
datetime_yrs=[datetime.date(int(y),1,1)表示listyear中的y]

您能展示一下您的尝试吗?您的输入和输出是什么?您关心这个月还是可以修改它?如果你真的在意,那么没有几个月的年份应该被认为是当年的一月一号还是类似的呢?@MorganThrapp:你的评论很有建设性。这件事有点奇怪。
#!/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]