Subtracting Dates With Python

后端 未结 5 800
攒了一身酷
攒了一身酷 2020-12-30 21:19

I\'m working on a simple program to tell an individual how long they have been alive.

I know how to get the current date, and get their birthday. The only problem is

相关标签:
5条回答
  • 2020-12-30 21:57

    Create a datetime.datetime from your date:

    datetime.datetime.combine(birthdate, datetime.time())
    

    Now you can subtract it from datetime.datetime.now().

    >>> from datetime import date, datetime, time
    >>> bday = date(1973, 4, 1)
    >>> datetime.now() - datetime.combine(bday, time())
    datetime.timedelta(14392, 4021, 789383)
    >>> print datetime.now() - datetime.combine(bday, time())
    14392 days, 1:08:13.593813
    
    0 讨论(0)
  • 2020-12-30 21:57
    import datetime
    born = datetime.date(2002, 10, 31)
    today = datetime.date.today()
    age = today - born
    
    print(age.total_seconds())
    

    Output: 463363200.0

    0 讨论(0)
  • 2020-12-30 21:59

    Use UTC time otherwise age in seconds can go backwards during DST transition:

    from datetime import datetime
    
    born = datetime(1981, 12, 2) # provide UTC time
    age = datetime.utcnow() - born
    print(age.total_seconds())
    

    You also can't use local time if your program runs on a computer that is in a different place (timezone) from where a person was born or if the time rules had changed in this place since birthday. It might introduce several hours error.

    If you want to take into account leap seconds then the task becomes almost impossible.

    0 讨论(0)
  • 2020-12-30 22:08
    from datetime import datetime
    
    birthday = datetime(1988, 2, 19, 12, 0, 0)
    diff = datetime.now() - birthday
    print diff
    # 8954 days, 7:03:45.765329
    
    0 讨论(0)
  • 2020-12-30 22:08

    When substracting two datettime objects you will get a datettime.timedelta object.

    from datettime import datetime
    x = datetime.now()
    y = datetime.now()
    delta = y - x
    

    It will give you the time difference with resolution to microsencods.

    For more information take a look at the official documentation

    0 讨论(0)
提交回复
热议问题