大家好,很高興你可以看到這篇小小的隨筆,
本文緣起于近日在團隊中給小白同事科普Python的使用,在留作業時想到了這個題目“通過給定日期和間隔日期天數,得到間隔日期天數后的日期和星期”,
本以為是道簡單題目,自己在實作時發現有點兒意思,于是post于此以供回憶,
其實題目的思路很簡單,就是利用Python中的時間序列(時間戳)將輸入日期轉換成時間戳,并將間隔天數也轉換成對應的總秒數,之后兩者相加得到一個新的時間戳,再將新的時間戳轉換成輸出的日期/星期等形式即可,其中需要考慮兩個問題:1)輸入的日期需要進行統一的格式化,2)Python的時間戳的起始時間是“1970年1月1日0時0分1秒”,如果輸入的日期或是計算間隔后的日期是早于這個系統的設定點會發生錯誤,
相似的操作在Excel中也可以實作,在Windows版中Excel的時間序列最早的日期是“1900年1月1日”,Mac版本請查閱相關資料,
最后是代碼實作,這應該只是其中的一種可能,留此供自己日后需要參照,
1 # 設計一個函式,輸入值為指定日期和間隔天數,輸出值為指定日期在經過間隔天數之后的日期和星期, 2 import time 3 4 def DateDeltaCal(SpecificDate,DeltaDateValue): 5 try: 6 # Format Input Date data 7 timeArray = time.strptime(SpecificDate, "%Y-%m-%d") 8 timeStamp = int(time.mktime(timeArray)) 9 10 # Calculate Delta Second 11 DeltaMSecond = int(DeltaDateValue * 86400) 12 13 # Delta Time Stamp 14 DeltaResult = timeStamp + DeltaMSecond 15 16 # Convert Time Stamp to recoganized format 17 localTime = time.localtime(int(DeltaResult)) 18 dateResult = time.strftime("%Y-%m-%d", localTime) 19 weekdayResult = time.strftime("%A", localTime) 20 21 return dateResult,weekdayResult 22 23 except: 24 print("Wrong format (should like: YYYY-MM-DD) or earlier than year 1970.") 25 26 # Input specific date and delta days 27 CurrentDate = "2020-6-1" 28 DeltaDate = -137 29 OutputResult = DateDeltaCal(CurrentDate,DeltaDate) 30 31 # Formatted to print results 32 print("Passed %d day(s) from %s, it will be %s, %s." %(DeltaDate,CurrentDate,OutputResult[0],OutputResult[1])) 33 34 print("\n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/5112.html
標籤:其他
上一篇:程式員擺地攤能接到活嗎?碼農地攤賣什么能掙到外快錢?
下一篇:運算子優先級
