Bobby B
Bobby B

Reputation: 2325

Parse date/time from a string

I'm using Python 3.3. I'm getting an email from an IMAP server, then converting it to an instance of an email from the standard email library.

I do this:

message.get("date")

Which gives me this for example:

Wed, 23 Jan 2011 12:03:11 -0700

I want to convert this to something I can put into time.strftime() so I can format it nicely. I want the result in local time, not UTC.

There are so many functions, deprecated approaches and side cases, not sure what is the modern route to take?

Upvotes: 1

Views: 465

Answers (3)

Bobby B
Bobby B

Reputation: 2325

Do this:

import email, email.utils, datetime, time    

def dtFormat(s):
  dt = email.utils.parsedate_tz(s)
  dt = email.utils.mktime_tz(dt)
  dt = datetime.datetime.fromtimestamp(dt)
  dt = dt.timetuple()
  return dt

then this:

s = message.get("date")    # e.g. "Wed, 23 Jan 2011 12:03:11 -0700"
print(time.strftime("%Y-%m-%d-%H-%M-%S", dtFormat(s)))

gives this:

2011-01-23-21-03-11

Upvotes: 0

kharandziuk
kharandziuk

Reputation: 12880

I use python-dateutil for parsing datetime strings. Function parse from this library is very handy for this kind of task

Upvotes: 1

TerryA
TerryA

Reputation: 59974

Something like this?

>>> import time
>>> s = "Wed, 23 Jan 2011 12:03:11 -0700"
>>> newtime = time.strptime(s, '%a, %d %b %Y %H:%M:%S -0700')
>>> print(time.strftime('Two years ago was %Y', newtime))
Two years ago was 2011 # Or whatever output you wish to receive.

Upvotes: 4

Related Questions