2018年8月23日 星期四

[ Python 文章收集 ] How To Convert Timestamp To Date and Time in Python

Source From Here 
Preface 
There are multiple ways how you can convert timestamp to human readable form in Python. For this conversion you may either use module datetime or time. 

Using module datetime 
Module datetime provides classes for manipulating date and time in more object oriented way: 
>>> from datetime import datetime
>>> dobj = datetime.fromtimestamp(1534906946)
>>> dobj.__class__

>>> dobj.isoformat()
'2018-08-22T11:02:26'

Using module time 
Another possibility to use function ctime from module time
>>> import time
>>> tobj = time.ctime(1534906946)
>>> tobj.__class__

>>> tobj
'Wed Aug 22 11:02:26 2018'

Formatting 
For custom human readable format you may use function strftime
>>> from datetime import datetime
>>> ts = int(time.time()) # Get timestamp
>>> dobj = datetime.fromtimestamp(ts) # Translate timestamp into datetime object
>>> print(dobj.strftime("%Y-%m-%d %H:%M:%S"))
2018-08-23 16:07:08
>>> print(dobj.strftime("%x %X"))
08/23/18 16:07:08
>>> print(dobj.strftime("%c"))
Thu Aug 23 16:07:08 2018
>>> print(dobj.strftime("%s"))
1535011628


Supplement 
PYTHON-基礎-時間日期處理小結

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...