将数字转换为d

2024-04-20 06:56:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: matplotlib格式绘制数字数组int年份listyearandmonth
1条回答
网友
1楼 · 发布于 2024-04-20 06:56:56

因为您没有提到任何与日期相关的数据,所以我所做的只是将两个列表中的给定年份转换为^{}对象,如Matplotlib's date APIdate 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]

相关问题 更多 >