转换为unix时间戳

转换为unix时间戳

本文介绍了在Python中,如何将此格式转换为unix时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Mon Jul 09 09:20:28 +0000 2012 

如果我有一个这样的格式作为一个STRING,我该怎么把它变成一个unix时间戳?



注意:我从Twitter的API获得这种格式:



解决方案

最好的选择是使用 dateutil.parser.parse(),它给你一个 datetime 对象与正确的时区信息:

 >>> import dateutil.parser 
>>> dt = dateutil.parser.parse('Mon Jul 09 09:20:28 +0200 2012')
>>> dt
datetime.datetime(2012,7,9,9,20,28,tzinfo = tzoffset(None,7200))

现在您只需要将其转换为UNIX时间戳记:

 >> ;进口时间
>>>> int(time.mktime(dt.timetuple()))
1341822028






您可以使用:

 >>> import datetime 
>>>> import email.utils
>>> parts = email.utils.parsedate_tz('Mon Jul 09 09:20:28 +0200 2012')
>>> dt = datetime.datetime(* parts [:6]) - datetime.timedelta(seconds = parts [-1])$ ​​b $ b>>> str(dt)
'2012-07-09 07:20:28'

这个实际上是在Python 3.3中实现了如何 email.utils.parsedate_to_datetime (如果要复制并粘贴到项目中,请替换 __ parsedate_tz with parsedate_tz from email.utils ):



pre $ def parsedate_to_datetime(data):
如果不是数据:
return None
* dtuple,tz = __parsedate_tz(data)
if tz是None:
return datetime.datetime(* dtuple [:6])
return datetime.datetime(* dtuple [:6],
tzinfo = datetime.timezone(datetime.timedelta秒= tz)))


Mon Jul 09 09:20:28 +0000 2012

If I have a format like that as a STRING, how can I turn it into a unix timestamp?

Note: I'm getting this format from Twitter's API:

https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitter

解决方案

The best option is using dateutil.parser.parse() which gives you a datetime object with proper timezone information:

>>> import dateutil.parser
>>> dt = dateutil.parser.parse('Mon Jul 09 09:20:28 +0200 2012')
>>> dt
datetime.datetime(2012, 7, 9, 9, 20, 28, tzinfo=tzoffset(None, 7200))

Now you just need to convert it to a UNIX timestamp:

>>> import time
>>> int(time.mktime(dt.timetuple()))
1341822028


The format you have can also be easily parsed using email.utils.parsedate_tz:

>>> import datetime
>>> import email.utils
>>> parts = email.utils.parsedate_tz('Mon Jul 09 09:20:28 +0200 2012')
>>> dt = datetime.datetime(*parts[:6]) - datetime.timedelta(seconds=parts[-1])
>>> str(dt)
'2012-07-09 07:20:28'

This is actually how email.utils.parsedate_to_datetime in Python 3.3 is implemented (if you want to copy&paste this into your project, replace __parsedate_tz with parsedate_tz from email.utils):

def parsedate_to_datetime(data):
    if not data:
        return None
    *dtuple, tz = __parsedate_tz(data)
    if tz is None:
        return datetime.datetime(*dtuple[:6])
    return datetime.datetime(*dtuple[:6],
            tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))

这篇关于在Python中,如何将此格式转换为unix时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:36