Python 处理理时间超详细转的

简介: # -*- coding: utf-8 -*- import time def timestamp_datetime(value):    format = '%Y-%m-%d %H:%M:%S'    # value为传入的值为时间戳(整形),如:1332888820    value = time.

# -*- coding: utf-8 -*-

import time

def timestamp_datetime(value):
    format = '%Y-%m-%d %H:%M:%S'
    # value为传入的值为时间戳(整形),如:1332888820
    value = time.localtime(value)
    ## 经过localtime转换后变成
    ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)
    # 最后再经过strftime函数转换为正常日期格式。
    dt = time.strftime(format, value)
    return dt

def datetime_timestamp(dt):
     #dt为字符串
     #中间过程,一般都需要将字符串转化为时间数组
     time.strptime(dt, '%Y-%m-%d %H:%M:%S')
     ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1)
     #将"2012-03-28 06:53:40"转化为时间戳
     s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
     return int(s)

if __name__ == '__main__':
    d = datetime_timestamp('2012-03-28 06:53:40')
    print d
    s = timestamp_datetime(1332888820)
    print s

 

 

---------------------------------------------------------------------------

 

(1)例如格式2012-07-31 00:01:18,根据该时间计算时间戳:

将"2012-03-28 06:53:40"转化为时间戳
s = time.mktime(time.strptime('2012-03-28 06:53:40', '%Y-%m-%d %H:%M:%S'))

(2)根据时间戳得到如2012-07-31 00:01:18的时间格式,显示的时间形式可以根据format指定的

import time

timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime("2012-07-31 00:01:18"))

 

时间戳转时间

tValue = time.localtime(int(str(value)[:10])

dt = time.strftime(format, tValue)

目录
相关文章
|
网络安全 Python
Python:获取ssl证书信息和到期时间
Python:获取ssl证书信息和到期时间
861 0
|
机器学习/深度学习 Python
Python中LSTM回归神经网络的时间序列预测
Python中LSTM回归神经网络的时间序列预测
913 2
Python中LSTM回归神经网络的时间序列预测
|
存储 Python
datetime库:Python日期与时间值管理计算(二)
datetime库:Python日期与时间值管理计算(二)
621 1
datetime库:Python日期与时间值管理计算(二)
|
C++ Python
Acwing 游戏时间 C++ python
Acwing 游戏时间 C++ python
415 0
Acwing 游戏时间 C++ python
python 如何将时间输出为年月的形式
python 如何将时间输出为年月的形式
python 如何将时间输出为年月的形式
|
索引 Python
python——时间模块
python——时间模块
python——时间模块
|
算法 Python
考点:角度旋转、海龟坐标轴以及简单时间绘图算法以及海龟的定时器ontimer【Python习题10】
考点:角度旋转、海龟坐标轴以及简单时间绘图算法以及海龟的定时器ontimer【Python习题10】
423 0
考点:角度旋转、海龟坐标轴以及简单时间绘图算法以及海龟的定时器ontimer【Python习题10】
|
Python
datetime库:Python日期与时间值管理计算(一)
datetime库:Python日期与时间值管理计算(一)
412 0
datetime库:Python日期与时间值管理计算(一)
|
编解码 Unix 知识图谱
time库:Python的时间时钟处理
time库:Python的时间时钟处理
521 0
time库:Python的时间时钟处理

推荐镜像

更多