How to use Python to calculate time

前端 未结 5 1016
傲寒
傲寒 2021-02-05 22:32

I want to write python script that acts as a time calculator.

For example:

Suppose the time is now 13:05:00

I want to add 1 hour, 23 minutes, and 10 seco

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 22:42

    For calculating dates and times there are several options but I will write the simple way:

    import datetime
    import dateutil.relativedelta
    
    # current time
    date_and_time = datetime.datetime.now()
    date_only = date.today()
    time_only = datetime.datetime.now().time()
    
    # calculate date and time
    result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)
    
    # calculate dates: years (-/+)
    result = date_only - dateutil.relativedelta.relativedelta(years=10)
    
    # months
    result = date_only - dateutil.relativedelta.relativedelta(months=10)
    
    # days
    result = date_only - dateutil.relativedelta.relativedelta(days=10)
    
    # calculate time 
    result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)
    result.time()
    

    Hope it helps

提交回复
热议问题