如何实现对指定日期进行增减日期操做结果的输出

你们好,很高兴你能够看到这篇小小的随笔。函数

本文缘起于近日在团队中给小白同事科普Python的使用,在留做业时想到了这个题目“经过给定日期和间隔日期天数,获得间隔日期天数后的日期和星期”。post

本觉得是道简单题目,本身在实现时发现有点儿意思,因而post于此以供回忆。spa

 

其实题目的思路很简单,就是利用Python中的时间序列(时间戳)将输入日期转换成时间戳,并将间隔天数也转换成对应的总秒数,以后二者相加获得一个新的时间戳,再将新的时间戳转换成输出的日期/星期等形式便可。其中须要考虑两个问题:1)输入的日期须要进行统一的格式化,2)Python的时间戳的起始时间是“1970年1月1日0时0分1秒”,若是输入的日期或是计算间隔后的日期是早于这个系统的设置点会发生错误。设计

类似的操做在Excel中也能够实现,在Windows版中Excel的时间序列最先的日期是“1900年1月1日”,Mac版本请查阅相关资料。code

 

最后是代码实现,这应该只是其中的一种可能,留此供本身往后须要参照。orm

 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")
相关文章
相关标签/搜索