简体   繁体   中英

Convert email (rfc 2822) date string to another format (ISO 8601 timestamp) in Python 2.7

I have dates of this format Thu, 18 Feb 2016 15:33:10 +0200

and I want them transformed to 2016-02-12 08:39:09.653475

How can this be achieved with the Python's standard library?

You can do this with the datetime module as follows:

from datetime import datetime

d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z').strftime('%Y-%m-%d %H:%M:%S.%f')

Or in python2 you may use instead:

from datetime import datetime
from dateutil.parser import parse

d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strftime(parse(d), '%Y-%m-%d %H:%M:%S.%f')

or if need to stick with standard library have a look at JFSebastian's comment at How to parse dates with -0400 timezone string in python?

check this link How to print date in a regular format in Python?

import time
import datetime

print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")


print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")

That will print out something like this:

Time in seconds since the epoch:    1349271346.46
Current date and time:              2012-10-03 15:35:46.461491
Or like this:                       12-10-03-15-35
Current year:                       2012
Month of year:                      October
Week number of the year:            40
Weekday of the week:                3
Day of year:                        277
Day of the month :                  03
Day of week:                        Wednesday

To parse the input date format using only stdlib, you could use email.utils package:

>>> from datetime import datetime, timedelta
>>> from email.utils import parsedate_tz, mktime_tz
>>> timestamp = mktime_tz(parsedate_tz('Thu, 18 Feb 2016 15:33:10 +0200'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> str(utc_time)
'2016-02-18 13:33:10'

where str(dt) is equivalent to dt.isoformat(' ') .

If you need to support leap seconds; (assuming your platform supports them) use tt = time.gmtime(timestamp) and time.strftime('%Y-%m-%d %H:%M:%S', tt) . Note: time.gmtime() may have different limits on different platforms (that are probably less than datetime 's limits).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM