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


    大家好,很高兴你可以看到这篇小小的随笔。

    本文缘起于近日在团队中给小白同事科普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("
    ")
  • 相关阅读:
    EasyUI tab
    CC和他的AE86
    Spreading the Wealth UVA
    Ultra-QuickSort POJ
    区间完全覆盖问题(贪心)
    Mod Tree HDU
    Snakes and Ladders LightOJ
    There is no SSR CSU
    X问题 HDU
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/bleurichard/p/13123638.html
Copyright © 2020-2023  润新知