Search code examples
pythondatetimestrptime

How to turn the value of a variable into a datetime object


I have an input in tkinter where a date is entered in the format of dd/mm/yyyy . I would like to make a variable equal to the three letter version of the month and another to be equal to the yyyy of a month.

the input variable is date_entry and I've tried

ss_date = date_entry.strftime("%d/%m/%Y")

and

ss_date = (datetime.strptime(date_entry, "%d/%m%Y"))

but i keep getting module 'datetime' has no attribute 'strptime'

I've looked online but every example uses datetime to generate an example in the first place, I cannot find any explanation of how to extract it from a variable value.

```
ss_date = date_entry.strftime("%d/%m/%Y") and
ss_date = (datetime.strptime(date_entry, "%d/%m%Y"))
```

module 'datetime' has no attribute 'strptime'

Can you please help.


Solution

  • Please make sure you import datetime correctly. Python has a library datetime which then also has a datetime object in it. So either import the object version directly, or call it by the 'full name' (datetime.datetime).

    Object version:

    from datetime import datetime
    date_entry = "04/05/2019"
    datetime.strptime(date_entry, "%d/%m/%Y")
    

    'Full name' version:

    import datetime
    date_entry = "04/05/2019"
    datetime.datetime.strptime(date_entry, "%d/%m/%Y")