python - Python - 为什么在转换日期格式时会出现此错误?
问题描述
当我尝试将日期格式转换为 mongodb 更好理解的内容时出现错误:
Traceback (most recent call last):
File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 516, in <module>
main()
File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 505, in main
print_reports()
File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 363, in print_reports
inputDate = inputDate.strftime(format)
AttributeError: 'str' object has no attribute 'strftime'
这是我的代码:
def print_reports():
inputDate = input("Enter the date in format 'dd/mm/yyyy': ")
day,month,year = inputDate.split('/')
isValidDate = True
try:
datetime(int(year),int(month),int(day))
except ValueError :
isValidDate = False
format= "%m%d%Y"
inputDate = inputDate.strftime(format)
我究竟做错了什么?
解决方案
inputDate
是str
对象,不是对象date
。
strftime()
是属于datetime
类的方法。如果要将字符串解析为日期,则需要执行以下操作:
inputDate = input("Enter the date in format 'dd/mm/yyyy': ")
my_date = datetime.strptime(inputDate,"%d/%m/%Y") # Notice that you can parse the date
# directly, without splitting the values
print(my_date.strftime("%Y-%m-%d")) # You can now output the date in any format you want
推荐阅读
- python - 在python中使用函数返回true或false
- forms - 尝试通过setter读取springboot项目中jsp表单提交返回的值,并使用组合调用另一个java类
- java - 谷歌登录 ApiException:10:
- web-applications - 如何从多个 html 文档中提取 URI?
- java - JLabel 不会更新,使用定时器每 3 秒更新一次时间
- python - 如何更改 DataFrame 中值的长度
- python - 附加到来自 SQL 的列表结果
- ios - 在 iOS 运行时禁用 crashlytics/Fabric
- out-of-memory - ArrayFire CPU,它会因为迟到的GC而耗尽内存吗?
- javascript - 无法使用 jquery 插件从图像裁剪中获取值