Python中的时间日期转换

简介: Python关于时间日期有两个库datetime和time,于是我们要在四种格式之间转换: datetime.datetime对象 datetime.datetime.now() time.

Python关于时间日期有两个库datetime和time,于是我们要在四种格式之间转换:
datetime.datetime对象 datetime.datetime.now()
time.struct_time对象  time.localtime()
字符串 "2010-12-04T10:30:53"
时间戳 1291433453  (一般我们不关心微秒)

列一下它们的转换方法:

dt = datetime.datetime(2010, 12, 4, 10, 30, 53)
dt = datetime.datetime.strptime("2010-12-04T10:30:53", "%Y-%m-%dT%H:%M:%S")
dt.strftime("%Y-%m-%dT%H:%M:%S")     ->   "2010-12-04T10:30:53"
或者 dt.isoformat().split(".").pop(0)     ->   "2010-12-04T10:30:53"
dt = datetime.datetime.fromtimestamp(1291433453)
(?) dt -> 1291433453

t = time.localtime(1291433453)
t = dt.timetuple()
t = time.strptime("2010-12-04T10:30:53", "%Y-%m-%dT%H:%M:%S")
t.strftime("%Y-%m-%dT%H:%M:%S")     ->   "2010-12-04T10:30:53"
long( time.mktime(t) )  ->  1291433453
(?) t -> dt


可以看出,Python没有提供直接的time.struct_time对象到datetime.datetime对象的转换,也没有直接提供datetime.datetime对象到时间戳的转换。另外,Python的两个strftime ,strptime中都没有时间戳的格式化符号。

对time.struct_time对象到datetime.datetime对象的转换,很容易想到通过字符串形式过渡一下:

dt = datetime.datetime.strptime(t.strftime("%Y-%m-%dT%H:%M:%S"), "%Y-%m-%dT%H:%M:%S")


更好的方式应该是这样

dt = datetime.datetime(*tuple(t)[:6])



对于datetime.datetime对象到时间戳的转换,常用做法是通过time.struct_time对象过渡:

long(time.mktime(dt.timetuple()))


坏处是要同时用到datetime和time两个模块。
其实可以在datetime内部解决,现在给一个三种格式转为时间戳的方法:

def to_timestamp(mytime, format="%Y-%m-%dT%H:%M:%S"):
    import time
    from datetime import datetime
    if isinstance(mytime, time.struct_time):
        return long(time.mktime(mytime))
    elif isinstance(mytime, str):
        mytime = datetime.strptime(mytime, format)
    if isinstance(mytime, datetime):
        #得到一个与时间戳相等的datetime.timedelta对象
        delta = mytime - datetime(1970,1,1)
        utc = delta.days * 86400L + delta.seconds
        #上面求得delta是一个localtime操作,把时区也考虑进去了,我们要还原
        return utc - 8 * 3600 



long(dt.strftime("%s"))
 

 

目录
相关文章
|
网络安全 Python
Python:获取ssl证书信息和到期时间
Python:获取ssl证书信息和到期时间
366 0
|
5月前
|
JSON 编解码 Linux
Python笔记1(赋值、浅拷贝和深拷贝、字符串日期转换、argparse、sys、overwrite、eval、json.dumps/json.loads、os.system(cmd)、zfill)
Python笔记1(赋值、浅拷贝和深拷贝、字符串日期转换、argparse、sys、overwrite、eval、json.dumps/json.loads、os.system(cmd)、zfill)
38 0
Python笔记1(赋值、浅拷贝和深拷贝、字符串日期转换、argparse、sys、overwrite、eval、json.dumps/json.loads、os.system(cmd)、zfill)
|
8月前
|
Python
Python的知识点运用-1(日期转换)
Python的知识点运用-1(日期转换)
45 0
|
机器学习/深度学习 Python
Python中LSTM回归神经网络的时间序列预测
Python中LSTM回归神经网络的时间序列预测
469 2
Python中LSTM回归神经网络的时间序列预测
|
C++ Python
Acwing 游戏时间 C++ python
Acwing 游戏时间 C++ python
63 0
Acwing 游戏时间 C++ python
python 如何将时间输出为年月的形式
python 如何将时间输出为年月的形式
python 如何将时间输出为年月的形式
|
索引 Python
python——时间模块
python——时间模块
python——时间模块
|
算法 Python
考点:角度旋转、海龟坐标轴以及简单时间绘图算法以及海龟的定时器ontimer【Python习题10】
考点:角度旋转、海龟坐标轴以及简单时间绘图算法以及海龟的定时器ontimer【Python习题10】
131 0
考点:角度旋转、海龟坐标轴以及简单时间绘图算法以及海龟的定时器ontimer【Python习题10】
|
存储 Python
datetime库:Python日期与时间值管理计算(二)
datetime库:Python日期与时间值管理计算(二)
301 1
datetime库:Python日期与时间值管理计算(二)
|
Python
datetime库:Python日期与时间值管理计算(一)
datetime库:Python日期与时间值管理计算(一)
188 0
datetime库:Python日期与时间值管理计算(一)

热门文章

最新文章