0

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

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks... but I need only the date... not time
print (date.date()) . This gives u just the date
Yes!... that's what I want. Thanks @saranya
0

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)))

Comments

0

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.

Comments

0
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

2 Comments

Thanks. But it is throwing the following error: ValueError: time data 'Sat, 21 Jan 2017 05:08:04 -0800' does not match format '%a %d %b %Y %X -%f'
@chhibbz sorry!!.Edited comma missing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.