【问题标题】:Displaying age in seconds using Python3使用 Python3 以秒为单位显示年龄
【发布时间】:2019-05-19 04:25:14
【问题描述】:

我想复制 Paul Erdoes 小时候使用的技巧: 根据他的出生日期和当前时间,告诉某人他老了多少秒。

这是当前代码的样子:

# For displaying age in seconds
from datetime import datetime

year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))


# This is resulting in datetime.timedelta object with attr days, seconds, microseconds
#delta = datetime.now() - datetime(year, month, day)
print("You are " + str(datetime.now() - datetime(year, month, day)) + " seconds old.")

#str(delta.seconds)

结果大约是 770xx 秒,但这是不正确的,因为每天已经是 36000 * 24 秒。

那么我该如何使用 datetime 库来执行我想做的事情呢?

【问题讨论】:

    标签: python python-3.x datetime


    【解决方案1】:

    您可以使用total_seconds 计算两个日期之间的秒差

    from datetime import datetime
    
    year = int(input("year: "))
    month = int(input("month: "))
    day = int(input("day: "))
    
    #Calculate time in seconds between now and the day of birth
    time_in_seconds = (datetime.now() - datetime(year=year, month=month, day=day)).total_seconds()
    
    print("You are {} seconds old.".format(time_in_seconds))
    

    输出将是

    year: 1991
    month: 1
    day: 31
    You are 892979995.504128 seconds old.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2011-06-10
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多