python 时间函数

python 时间有四种表达,时间元组,string, datetime,时间戳。

//时间元组
import time
time.localtime()
//time.struct_time(tm_year=2019, tm_mon=7, tm_mday=16, tm_hour=18, tm_min=40, tm_sec=33, tm_wday=1, tm_yday=197, tm_isdst=0)

// string
str_time = '2019-07-16 18:41:30'

// datetime
import datetime
datetime.datetime.now()
// datetime.datetime(2019, 7, 16, 18, 42, 35, 201000)

// 时间戳
import time
time.time()
// 1563273807.836

时间元组转其他格式

import time
import datetime

st = time.localtime()
//转string
str_time = time.strftime('%Y-%m-%d %H:%M:%S', st)
// 2019-07-16 18:47:35

//转datetime
dt = datetime.datetime(*t[0:6])
//datetime.datetime(2019, 7, 16, 18, 47, 35)

//转时间戳
timestamp = time.mktime(st)

string转其他格式

import time
import datetime

str_time = '2019-07-16 18:41:30'
//转时间元组
st = time.strptime(str_time, '%Y-%m-%d %H:%M:%S')
//time.struct_time(tm_year=2019, tm_mon=7, tm_mday=16, tm_hour=18, tm_min=41, tm_sec=30, tm_wday=1, tm_yday=197, tm_isdst=-1)

//转datetime
dt = datetime.datetime.strptime(str_time , "%Y-%m-%d %H:%M:%S")
//datetime.datetime(2019, 7, 16, 18, 41, 30)

//转时间戳
timestamp = time.mktime(time.strptime(str_time, '%Y-%m-%d %H:%M:%S'))

datetime转其他格式

import datetime
import time

dt = datetime.datetime.now()

// e转string
str_time = dt.strftime("%Y-%m-%d %H:%M:%S")
// '2019-07-16 19:03:21'

//转时间元组
st = dt.timetuple()
// time.struct_time(tm_year=2019, tm_mon=7, tm_mday=16, tm_hour=19, tm_min=3, tm_sec=54, tm_wday=1, tm_yday=197, tm_isdst=-1)

// 转时间戳
timestamp = time.mktime(dt.timetuple())
1563275150.0

时间戳转其他

import time
import datetime

timestamp  = time.time()
// 1493731831.136

// 转datetime
dt = datetime.datetime.fromtimestamp(timestamp)
datetime.datetime(2019, 7, 16, 19, 7, 29, 40000)


// 转时间元组
st = time.localtime(timestamp)
# time.struct_time(tm_year=2019, tm_mon=7, tm_mday=16, tm_hour=19, tm_min=8, tm_sec=23, tm_wday=1, tm_yday=197, tm_isdst=0)

//转string
str_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(timestamp  ))

strftime跟strptime的区别

strftime时将时间转成特定格式的字符串

import time
t = time.localtime()
//time.struct_time(tm_year=2019, tm_mon=7, tm_mday=16, tm_hour=19, tm_min=22, tm_sec=55, tm_wday=1, tm_yday=197, tm_isdst=0)
str_time = time.strftime('%Y-%m-%d %H:%M:%S', t)
// '2019-07-16 19:23:31'

而strptime正好相反,是将字符串转成时间格式

s = '2019-07-16 19:24:33'
t = time.strptime(s, '%Y-%m-%d %H:%M:%S')
// time.struct_time(tm_year=2019, tm_mon=7, tm_mday=16, tm_hour=19, tm_min=24, tm_sec=33, tm_wday=1, tm_yday=197, tm_isdst=-1)

你可能感兴趣的:(python 时间函数)