我的目標是開發一個創建串列 target_list 的函式,見下文。目標串列具有以下結構,它始終以日期“1995-01-01”開頭,然后跟隨代表一年中接下來的 11 個月的 11 個元素。在“dec”之后,我想要一個新的日期字串“1996-01-01”,然后是去年的月份。
下面的目標串列長度為 27。我希望函式將 target_list 的長度作為引數。如果為 28,則將一個元素添加到 target_list('april')。
target_list=['1995-01-01','feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '1996-01-01',
'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '1997-01-01', 'feb', 'mar']
下面的代碼回傳我想要的串列。因為我想要一個 27 個月的串列,所以我回圈了 3 年。這迫使我洗掉串列的最后九個元素。我很難找到一種方法來使這個程序自動化。也許我想要一份 145 個月的清單。該函式必須知道要洗掉多少元素。這個我還沒想通。任何幫助或建議將不勝感激。當然,更有效的解決方案也很有趣。
import math
from datetime import datetime
from datetime import date
def add_years(d, years):
try:
return d.replace(year = d.year years)
except ValueError:
return d (date(d.year years, 1, 1) - date(d.year, 1, 1))
year=pd.to_datetime('1994-01-01')
years=math.ceil(27/12) #For 27 month I need three years. Use math.ceil to "round" upwards.
target=[]
for i in range(1,years 1): # Loop over the number of years
year=add_years(year,1) # Add one year for each loop
y=[year.strftime("%Y-%m-%d")]
z=y month # Concat the lists
target=target z # Concat with target
target_list=target[:len(target)-9] # Remove the last nine elements of the list
print(target_list)
這是一種解決方案。
def get_list(no_month):
import math
year=pd.to_datetime('1994-01-01')
years=math.ceil(no_month/12)
remove=(years*12)-no_month
target=[]
for i in range(1,years 1): # Loop over the number of years involved
year=add_years(year,1) # Add one year for each loop
y=[year.strftime("%Y-%m-%d")]
z=y month # Concat the lists
target=target z # Concat with target
target_list=target[:len(target)-remove]
return target_list
uj5u.com熱心網友回復:
我將按itertools如下方式用于此任務
import itertools
def months():
year = itertools.count(1995)
for m in itertools.cycle(['y', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec']):
yield '{}-01-01'.format(next(year)) if m=='y' else m
target145 = list(itertools.islice(months(),145))
print(target145)
輸出
['1995-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '1996-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '1997-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '1998-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '1999-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2000-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2001-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2002-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2003-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2004-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2005-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2006-01-01', 'feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec', '2007-01-01']
說明:首先我創建了無限的迭代器月份,在內部我itertools.cycle用來回圈月份代碼,我用y字母來表示年份應該出現在哪里,所以我next從 1995 年開始取年。我.format用來獲取所需的 str 持有年份,否則月份情況是按原樣提供。然后我得到 145 個無盡的第一個元素months()并將其轉換list為符合規定的要求。
uj5u.com熱心網友回復:
您想知道一整年還剩多少個月,可以使用模數:
months = 27
toRemove = 12 - (months % 12)
uj5u.com熱心網友回復:
您可以執行以下操作
from datetime import datetime, timedelta
def target_list(length=27):
target = []
start = datetime.strptime("1995-01-01", "%Y-%m-%d")
for i in range(length // 12 (1 if length % 12 != 0 else 0)):
target.extend([
start.replace(year=start.year i).strftime("%Y-%m-%d"),
'feb',
'mar',
'april',
'maj',
'jun',
'juli',
'aug',
'sep',
'okt',
'nov',
'dec',
])
return target[:length]
print(target_list())
這將用完整的 12 個值填充串列,然后將其切割給定長度
uj5u.com熱心網友回復:
date = "1995-01-01"
numberOfMonth = 27
month =['feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec']
date=int(date[0:4])
output = []
for i in range(numberOfMonth):
if not i%12:
output.append(str(date i//12) "-01-01")
else:
output.append(month[i%12-1])
print(output)
uj5u.com熱心網友回復:
from datetime import date
import pandas as pd
months = ['feb', 'mar', 'april', 'maj', 'jun', 'juli', 'aug', 'sep', 'okt', 'nov', 'dec']
def add_years(d, years):
"""Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
try:
return d.replace(year = d.year years)
except ValueError:
return d (date(d.year years, 1, 1) - date(d.year, 1, 1))
def create_target_list(n):
m = n//12 # floor division to get the number of times
date_zero = '1995-01-01'
date_zero=pd.to_datetime(date_zero)
target_list = []
for k in range(m):
target_list.append(str(date_zero)[:10])
target_list.extend(months)
date_zero = add_years(date_zero, 1)
if n%12 > 0 :
if n%12 == 1:
target_list.append(str(date_zero)[:10])
else :
target_list.append(str(date_zero)[:10])
target_list.extend(months[:n%12-1])
return target_list
#print(create_target_list(26))
uj5u.com熱心網友回復:
你可以這樣做:
from datetime import datetime
from dateutil.relativedelta import relativedelta
FORMAT = '%Y-%m-%d'
def genvals(start_date, length):
d = datetime.strptime(start_date, FORMAT)
for _ in range(length):
yield datetime.strftime(d, FORMAT) if d.month == 1 else d.strftime('%b')
d = relativedelta(months=1)
def genlist(start_date, length):
return [d for d in genvals(start_date, length)]
print(genlist('1994-01-01', 27))
輸出:
['1994-01-01', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '1995-01-01', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '1996-01-01', 'Feb', 'Mar']
筆記:
實際輸出將根據您的語言環境而有所不同
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436863.html
下一篇:如何計算熊貓的自定義會計年度?
