chhibbz
chhibbz

Reputation: 480

Changing datetime format in Python Language

I am parsing emails through Gmail API and have got the following date format:

Sat, 21 Jan 2017 05:08:04 -0800

I want to convert it into ISO 2017-01-21 (yyyy-mm-dd) format for MySQL storage. I am not able to do it through strftime()/strptime() and am missing something. Can someone please help?

TIA

Upvotes: 0

Views: 1604

Answers (4)

Smart Manoj
Smart Manoj

Reputation: 5851

from datetime import datetime 
s="Sat, 21 Jan 2017 05:08:04 -0800"
d=(datetime.strptime(s,"%a, %d %b %Y %X -%f"))
print(datetime.strftime(d,"%Y-%m-%d"))

Output : 2017-01-21

Upvotes: 0

Priyank Chheda
Priyank Chheda

Reputation: 571

You can even do it manually using simple split and dictionary.That way, you will have more control over formatting.

def dateconvertor(date):
    date = date.split(' ')
    month = {'Jan': 1, 'Feb': 2, 'Mar': 3}
    print str(date[1]) + '-' + str(month[date[2]]) + '-' + str(date[3])

def main():
    dt = "Sat, 21 Jan 2017 05:08:04 -0800"
    dateconvertor(dt)

if __name__ == '__main__':
    main()

Keep it simple.

Upvotes: 0

MSD
MSD

Reputation: 1407

isoformat() in the dateutil.

import dateutil.parser as parser
text = 'Sat, 21 Jan 2017 05:08:04 -0800'
date = (parser.parse(text))
print(date.isoformat())
print (date.date())

Output :

2017-01-21T05:08:04-08:00
2017-01-21

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249582

You can do it with strptime():

import datetime
datetime.datetime.strptime('Sat, 21 Jan 2017 05:08:04 -0800', '%a, %d %b %Y %H:%M:%S %z')

That gives you:

datetime.datetime(2017, 1, 21, 5, 8, 4, tzinfo=datetime.timezone(datetime.timedelta(-1, 57600)))

Upvotes: 0

Related Questions