2015-06-30 88 views
-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'] 
+4

你能告訴你有沒有試過? –

+1

你的輸入是什麼,你想要什麼輸出? –

+0

你關心這個月還是你可以修改它?如果你真的在意,那麼將這個月份的年份看作是那一年的第一年還是類似的? –

回答

0

既然你不提及任何日期相關的數據,所有我做的是從兩個列表中Matplotlib's date APIdate demo提到的轉換給定的年datetime.date對象:

#!/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]