社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用Python3以秒为单位显示年龄

StFi • 5 年前 • 1433 次点击  

我想复制保罗·埃尔多斯小时候玩过的把戏: 根据某人的出生日期和现在的时间,告诉他几秒钟的时间。

当前代码如下所示:

# 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/Django开发社区
本文地址:http://www.python88.com/topic/50880
 
1433 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Devesh Kumar Singh
Reply   •   1 楼
Devesh Kumar Singh    6 年前

你可以用 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.