时间的表示类型

py中可能涉及的time有四种类型

  1. time string
  2. datetime tuple(datetime obj)
  3. time tuple(time obj)
  4. timestamp

时区

time string

string 是最简单的表示时间的方式,如以下代码生成的即为 string:

  1. >>> time.ctime()
  2. 'Mon Dec 17 21:02:55 2012'

或者更简单的生成一个字符串:time_string = "2000-01-02 03:04:05"

datetime tuple(datetime obj)

datetime tuple 是 datetime.datetime 对象类型

  1. >>> datetime.now()
  2. datetime.datetime(2012, 12, 17, 21, 3, 44, 139715)

time tuple(time obj)

time tuple 是 time.struct_time 对象类型

  1. 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)

timestamp

时间戳类型: 自 1970年1月1日(00:00:00 GMT) 以来的秒数

  1. >>> time.time()
  2. 1355749338.05917

类型之间的转换

string 转换为其它

初始化: date_str = "2008-11-10 17:53:59"

string —> datetime obj

导入:

  1. import datetime
  2. datetime.datetime.strptime(string, format)
  3. >>> dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
  4. >>> dt_obj
  5. datetime.datetime(2008, 11, 10, 17, 53, 59)

string —> time obj

导入:

  1. import time
  2. time.strptime(string, format)
  3. #time模块有类似datetime中的strptime()函数
  4. >>> date_str = "2008-11-10 17:53:59"
  5. >>> t_obj = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
  6. >>> t_obj
  7. 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)

datetime obj转换为其它

datetime obj 转换为其它类型,用的都是 datetime 的函数。

初始化:

  1. dt_obj = datetime.datetime(2008, 11, 10, 17, 53, 59)

dt obj —> string

  1. date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")

dt obj —> time obj

  1. time_tuple = dt_obj.timetuple()

time obj转换为其它

初始化:

  1. time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)

time obj —> string

  1. date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)

time obj —> datetime obj

  1. datetime.datetime(*time_tuple[0:6])

time obj —> timestamp

  1. ts = time.mktime(time_tuple)

timestamp转换为其它

初始化: timestamp = 1226527167.595983

!!注意以下两种都使用local时区

timestamp —> dt obj

  1. dt_obj = datetime.fromtimestamp(timestamp)

timestamp —> time obj

  1. time_tuple = time.localtime(timestamp)

!!以下两种方式和时区相关,比较标准时区时间和本地时区时间

使用UTC —> dt obj

  1. #本地时区时间
  2. >>> datetime.datetime.fromtimestamp(tm)
  3. datetime.datetime(2012, 12, 17, 23, 39, 58, 401881)
  4. #标准时区时间
  5. >>> datetime.datetime.utcfromtimestamp(tm)
  6. datetime.datetime(2012, 12, 17, 15, 39, 58, 401881)

使用UTC —> time obj

  1. #本地时区时间
  2. >>> time.localtime(tm)
  3. 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)
  4. #标准时区时间
  5. >>> time.gmtime(tm)
  6. 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)