常遇到的变换过程举例
def time_stamp_to_str(timeStamp):
import datetime
datetime_obj = datetime.datetime.utcfromtimestamp(timeStamp) # timestamp to datetime
print(datetime_obj)
time_year_second = datetime_obj.strftime("%Y-%m-%d %H:%M:%S") # datetime to str
time_year_day = datetime_obj.strftime("%Y%m%d")
print("time_year_second", time_year_second)
print("time_year_day", time_year_day)
return time_year_day, time_year_second
time_stamp_to_str(1545470518) # 秒为单位, 若是ms OSError: [Errno 22] Invalid argument
# [out]
2018-12-22 09:21:58
time_year_second 2018-12-22 09:21:58
time_year_day 20181222
def time_str_date(date_str):
"""
date_str ‘20000215‘ -> 2000
:param date_str:
:return: year
"""
import datetime
try:
date_time = datetime.datetime.strptime(date_str, ‘%Y%m%d‘)
return date_time.year
except Exception as _:
return ‘‘
import time
time_str = ‘2018-12-22 17:21:58‘
time_tuple = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
print(time_tuple)
time_stamp = time.mktime(time_tuple)
print("time_stamp ==== ",time_stamp)
import time
t = 1545470518
tarray = time.localtime(t)
print(tarray)
time_str = time.strftime("%Y-%m-%d %H:%M:%S", tarray)
time_str
datetime 类型可以直接做比较,其方法有:dir(datetime_obj) 或 help(datetime_obj) , 创建datetime_obj快速方法
datetime.now()
arrow, maya 都号称是 datetime for humanize, 操作简单,看一下文档就会,真的很棒~
https://arrow.readthedocs.io/en/latest/
pip install arrow
arrow.get(‘2013-05-05 12:30:45‘, ‘YYYY-MM-DD HH:mm:ss‘)
arrow.get(2012,12,12)
arrow.get("2013-02-23", "YYYY-MM-DD")
arrow.get("20130223", "YYYYMMDD")
arrow.get("20130223", "YYYYMMDD").year
arrow.get("20130223", "YYYYMMDD").timestamp
一些举例:
import arrow
local = arrow.utcnow().to(‘US/Pacific‘)
local.format()
# Out[10]: u‘2018-12-02 21:21:37-08:00‘
print(arrow.now())
print(arrow.utcnow().to("Asia/Shanghai")) # 不能打错一个字母,不能有空格
print(arrow.utcnow().to("Asia/Hong_Kong"))
print(arrow.utcnow().to("Asia/Tokyo"))
print(arrow.utcnow().to("Asia/Seoul"))
lo = local.shift(hours=-2)
lo
arrow.get(‘2018-12-22T01:30:24.380226-08:00‘)
local.timestamp
local.format()
local.format("YYYY-MM-DD HH:mm:ss ZZ")
local.humanize()
local.humanize(locale="zh") # "ko_kr"
原文:https://www.cnblogs.com/bruspawn/p/10162327.html