简体   繁体   English

从字符串解析日期/时间

[英]Parse date/time from a string

I'm using Python 3.3. 我正在使用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 . 我从IMAP服务器收到一封电子邮件,然后将其从标准电子邮件库转换为电子邮件实例。

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. 我想将其转换为可以放入time.strftime()以便对其进行格式化。 I want the result in local time, not UTC. 我想要本地时间而不是UTC的结果。

There are so many functions, deprecated approaches and side cases, not sure what is the modern route to take? 功能太多,不赞成使用的方法和附带情况,不确定是否要采用现代方法?

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.

I use python-dateutil for parsing datetime strings. 我使用python-dateutil解析日期时间字符串。 Function parse from this library is very handy for this kind of task 从该库进行函数解析对于此类任务非常方便

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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