首页 > 解决方案 > 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)

我究竟做错了什么?

标签: python

解决方案


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

推荐阅读