Rachit Jha
Rachit Jha

Reputation: 11

Dictionary to datetime

I am looking to convert a string which is a date '31-Dec-2018' to datetime object: datetime.date(2018, 12, 31). Is there any built in method that can be helpful ?

Say I have a dictionary basedate that has date in it. I have to convert it to datetime object. I am trying this:

basedate = {date: '31-Dec-2018'}
datetimetime.strptime(basedate, '%dd-%MMM-%yyyy')

I am getting an error while converting the string to datetime which states that it does not match the %dd-%MM-%yyyy format

Upvotes: 1

Views: 96

Answers (2)

nurealam siddiq
nurealam siddiq

Reputation: 1623

Here's a solution to your specific problem:

First correct your dictionary as: basedate = {'date': '31-Dec-2018'}

Code:

from datetime import datetime

basedate = {'date': '31-Dec-2018'}
basedate = datetime.strptime(basedate['date'], '%d-%b-%Y').date()

Upvotes: 0

Snorre Løvås
Snorre Løvås

Reputation: 271

You need to use the correct format: https://docs.python.org/3/library/datetime.html?#strftime-strptime-behavior

And parse the actual string, not the dictionary.

datetime.strptime('31-Dec-2018','%d-%b-%Y')

Upvotes: 3

Related Questions