Why is datetime.strptime not working in this simple example?

前端 未结 6 1147
轻奢々
轻奢々 2020-12-08 09:24

I\'m using strptime to convert a date string into a datetime. According to the linked page, formatting like this should work:

>>> # Usi         


        
相关标签:
6条回答
  • 2020-12-08 09:52

    You are importing the module datetime, which doesn't have a strptime function.

    That module does have a datetime object with that method though:

    import datetime
    dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
    

    Alternatively you can import the datetime object from the module:

    from datetime import datetime
    dtDate = datetime.strptime(sDate, "%m/%d/%Y")
    

    Note that the strptime method was added in python 2.5; if you are using an older version use the following code instead:

    import datetime, time
    dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
    
    0 讨论(0)
  • 2020-12-08 09:52

    You can also do the following,to import datetime

    from datetime import datetime as dt
    
    dt.strptime(date, '%Y-%m-%d')
    
    0 讨论(0)
  • 2020-12-08 09:55

    You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.

    0 讨论(0)
  • 2020-12-08 09:57

    You should use strftime static method from datetime class from datetime module. Try:

    import datetime
    dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")
    
    0 讨论(0)
  • 2020-12-08 09:59

    If in the folder with your project you created a file with the name "datetime.py"

    0 讨论(0)
  • 2020-12-08 10:02

    Because datetime is the module. The class is datetime.datetime.

    import datetime
    dtDate = datetime.datetime.strptime(sDate,"%m/%d/%Y")
    
    0 讨论(0)
提交回复
热议问题