Python datetime和unix时间戳之间相互转换的讲解

liuxiaohua 2019-04-01

python datetime和unix时间戳之间相互转换

1、代码:

import time
  import datetime
  # 1、datetime转unix时间戳
  # (1)、逐个打印
  n = datetime.datetime.now() #当前时间
  a = n.timetuple()      
  b = time.mktime(a)
  c = int(b)
  # (2)、链式打印
  r = int(time.mktime(datetime.datetime.now().timetuple()))
  # 2、将unix时间戳转换为python的datetime
  u = 1439111214.0    #unix时间戳
  t = datetime.datetime.fromtimestamp(u)
  print('----- datetime => unix ------')
  print('------逐个打印------')
  print('n:',n)
  print('a:',a)
  print('b:',b)
  print('c:',c)
  print('------链式打印------')
  print('r:',r)
  print('----- unix => datetime ------')
  print('t:',t)

2、打印:

----- datetime => unix ------
  ------逐个打印------
  n: 2018-05-23 17:11:10.587935
  a: time.struct_time(tm_year=2018, tm_mon=5, tm_mday=23, tm_hour=17, tm_min=11, tm_sec=10, tm_wday=2, tm_yday=143, tm_isdst=-1)
  b: 1527066670.0
  c: 1527066670
  ------链式打印------
  r: 1527066670
  ----- unix => datetime ------
  t: 2015-08-09 17:06:54

相关推荐