我正在写一个'age to seconds'转换器,但我一直遇到各种错误。
#
!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime
print ('Welcome to a simple age to seconds converter. ')
def get_date():
print ('Please enter the year of your birth in the format YYYY, MM, DD:')
date_of_birth = str(input())
converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
date_now = datetime.strftime("%Y-%m-%d")
total_seconds = ((date_now - converted_date).days)*86400
return ('You have lived for:', total_seconds, 'seconds.')
print (get_date())
if __name__ == "__main__":
main()
我认为这是该程序最正确的版本,但我一直收到错误TypeError:描述符'strftime'需要'datetime.date'对象但收到'str'。
有谁知道我怎么纠正?还有如何计算输入日期到现在的精确时刻的秒数? 提前致谢
答案 0 :(得分:1)
date_now
应为datetime.now()
。在现有strftime("%Y-%m-%d")
实例上调用datetime
并返回一个字符串。
date_of_birth = input()
converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
date_now = datetime.now()
total_seconds = (date_now - converted_date).days * 24 * 60 * 60
# day: 24 h * 60 min * 60 sec = 86400 != 8640000
print('You have lived for:', total_seconds, 'seconds.')
答案 1 :(得分:0)
你直接从类调用方法strftime(),而不是在datetime实例上调用它。我在下面的代码中添加了.now():
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime
print ('Welcome to a simple age to seconds converter. ')
def get_date():
print ('Please enter the year of your birth in the format YYYY, MM, DD:')
date_of_birth = str(input())
converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
date_now = datetime.now()
total_seconds = ((date_now - converted_date).days)*8640000
return ('You have lived for:', total_seconds, 'seconds.')
print (get_date())
if __name__ == "__main__":
main()
编辑:我刚刚意识到代码中的下一行实际上可能会生成错误,因为从字符串中减去了一个日期时间实例。您可能希望完全删除.strftime()调用。