我正在写一个‘年龄到秒’的转换器,但我一直收到各种错误。
#
!/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’需要一个'datetime.date‘对象,但收到了一个'str’。
有人知道我怎么纠正这个问题吗?还有,如何计算到现在输入日期的精确时刻的秒数呢?提前感谢
发布于 2017-11-15 08:44:20
date_now
应为datetime.now()
。在现有的datetime
实例上调用strftime("%Y-%m-%d")
并返回一个字符串。
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.')
发布于 2017-11-15 08:43:34
您直接从类调用方法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()
编辑:我刚刚意识到代码中的下一行实际上可能会生成错误,因为之后会从字符串中减去datetime实例。您可能希望完全删除.strftime()调用。
https://stackoverflow.com/questions/47302742
复制相似问题