Python日期时间转换

# 将20130622000000 转化为unix时间戳
def conv_time(str_time_long):
    return int(time.mktime(time.strptime(str_time_long, "%Y%m%d%H%M%S")))

格式互转,需要使用datetime模块:

datetime.strptime(string, format):将日期字符串string,根据format,转化为datetime对象(六元数组)。

>>>> datetime.datetime.strptime('201311261010', '%Y%m%d%H%M%S')
>>>> datetime.datetime(2013, 11, 26, 10, 1)

datetime.strftime(format),将datetime对象,格式化输出成字符串。

>>> import datetime
>>> dt = datetime.datetime.strptime('201311261010', '%Y%m%d%H%M%S')
>>> dt.strftime('%Y-%m-%d %H:%M:%S')
'2013-11-26 10:01:00'

将datetime对象转化为UNIX时间戳:

>>>> print time.mktime(dt.timetuple())
>>>> 1385431260.0

 

Leave a Reply

Your email address will not be published.