Python字符串、时间戳、datetime时间相关转换
总结的时间转换函数
# datetime时间转为字符串 def Changestr(datetime1): str1 = datetime1.strftime('%Y-%m-%d %H:%M:%S') return str1 # 字符串时间转为时间戳 def Changetime(str1): Unixtime = time.mktime(time.strptime(str1, '%Y-%m-%d %H:%M:%S')) return Unixtime # datetime时间转为时间戳 def Changestamp(dt1): Unixtime = time.mktime(time.strptime(dt1.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) return Unixtime # 时间戳转为datetime时间 def Changedatetime(timestamp): dt = datetime.datetime.fromtimestamp(timestamp) return dt # uinx时间戳转换为本地时间 def Localtime(datetime1): Localtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(datetime1)) return Localtime # 字符串时间转换函数 def Normaltime(datetime1): Normaltime = datetime.datetime.strptime(datetime1,'%Y-%m-%d %H:%M:%S') return Normaltime
时间加一天,减一天,加减一小时一分钟,加减一年一月,时区转换
当前日期时间
import datetime print(datetime.datetime.now()) # 2018-05-08 16:53:30.101000
格式化时间
import datetime print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) # 2018-05-08 16:54
多加一天
import datetime print(datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S") # 2018-05-09 16:56:07
减一天
import datetime print (datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S") # 2018-05-07 16:56:59
其他类似
import datetime in_date = '2016-08-31' dt = datetime.datetime.strptime(in_date, "%Y-%m-%d") out_date = (dt + datetime.timedelta(days=2)).strftime("%Y-%m-%d") print(out_date) # 2016-09-02
可以把days改为hours minutes,就可以提前XX小时/分钟了。
减去一年
import datetime from dateutil.relativedelta import relativedelta d = datetime.datetime.strptime('20180131', '%Y%m%d') print(d) // 2018-01-31 00:00:00 print((d - relativedelta(years=1)).strftime('%Y%m%d')) // 20170131
还可以把years
改为months