------------------------
1. string 转换为其它
初始化:
date_str = "2008-11-10 17:53:59"
1.1 string --> datetime obj
导入:
import datetime
datetime.datetime.strptime(string, format)
eg
----------------------------------------------
>>> dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
>>> dt_obj
datetime.datetime(2008, 11, 10, 17, 53, 59)
----------------------------------------------
1.2 string --> time obj
导入:
import time
time.strptime(string, format)
eg
----------------------------------------------
#time模块有类似datetime中的strptime()函数
>>> date_str = "2008-11-10 17:53:59"
>>> t_obj = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
>>> t_obj
time.struct_time(tm_year=2008, tm_mon=11, tm_mday=10, tm_hour=17, tm_min=53, tm_sec=59, tm_wday=0, tm_yday=315, tm_isdst=-1)
----------------------------------------------
2. datetime obj转换为其它
datetime obj转换为其它类型,用的都是datetime的函数
初始化:
dt_obj = datetime.datetime(2008, 11, 10, 17, 53, 59)
2.1 dt obj --> string
----------------------------------------------
date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
----------------------------------------------
2.2 dt obj --> time obj
----------------------------------------------
time_tuple = dt_obj.timetuple()
----------------------------------------------
3. time obj转换为其它
初始化:
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
3.1 time obj --> string
----------------------------------------------
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
----------------------------------------------
3.2 time obj --> datetime obj
----------------------------------------------
datetime.datetime(*time_tuple[0:6])
----------------------------------------------
3.3 time obj --> timestamp
----------------------------------------------
ts = time.mktime(time_tuple)
----------------------------------------------
4. timestamp转换为其它
初始化:
timestamp = 1226527167.595983
--!!--注意以下两种都使用local时区
4.1 timestamp --> dt obj
----------------------------------------------
dt_obj = datetime.fromtimestamp(timestamp)
----------------------------------------------
4.2 timestamp --> time obj
----------------------------------------------
time_tuple = time.localtime(timestamp)
----------------------------------------------
--!!--以下两种方式和时区相关,比较标准时区时间和本地时区时间
4.3 使用UTC --> dt obj
----------------------------------------------
#本地时区时间
>>> datetime.datetime.fromtimestamp(tm)
datetime.datetime(2012, 12, 17, 23, 39, 58, 401881)
#标准时区时间
>>> datetime.datetime.utcfromtimestamp(tm)
datetime.datetime(2012, 12, 17, 15, 39, 58, 401881)
----------------------------------------------
4.4 使用UTC --> time obj
----------------------------------------------
#本地时区时间
>>> time.localtime(tm)
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=17, tm_hour=23, tm_min=39, tm_sec=58, tm_wday=0, tm_yday=352, tm_isdst=0)
#标准时区时间
>>> time.gmtime(tm)
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=17, tm_hour=15, tm_min=39, tm_sec=58, tm_wday=0, tm_yday=352, tm_isdst=0)
----------------------------------------------