1

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?

3 Answers 3

4

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Looking for something built-in which doesn't require any string manipulation. This code requires that I hardcode knowledge of the timezone.
1

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

Comments

0

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

Comments

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.