亲宝软件园·资讯

展开

python生成时间戳 python生成13位或16位时间戳以及反向解析时间戳的实例

宁致乐水 人气:7

我就废话不多说了,直接上代码吧!

import datetime
import time

def get_float_time_stamp():
  datetime_now = datetime.datetime.now()
  return datetime_now.timestamp()

def get_time_stamp16():
  # 生成16时间戳  eg:1540281250399895  -ln
  datetime_now = datetime.datetime.now()
  print(datetime_now)

  # 10位,时间点相当于从UNIX TIME的纪元时间开始的当年时间编号
  date_stamp = str(int(time.mktime(datetime_now.timetuple())))

  # 6位,微秒
  data_microsecond = str("%06d"%datetime_now.microsecond)

  date_stamp = date_stamp+data_microsecond
  return int(date_stamp)

def get_time_stamp13():
  # 生成13时间戳  eg:1540281250399895
  datetime_now = datetime.datetime.now()

  # 10位,时间点相当于从UNIX TIME的纪元时间开始的当年时间编号
  date_stamp = str(int(time.mktime(datetime_now.timetuple())))

  # 3位,微秒
  data_microsecond = str("%06d"%datetime_now.microsecond)[0:3]

  date_stamp = date_stamp+data_microsecond
  return int(date_stamp)

def stampToTime(stamp):
  datatime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(stamp)[0:10])))
  datatime = datatime+'.'+str(stamp)[10:]
  return datatime

if __name__ == '__main__':
  a1 = get_time_stamp16()
  print(a1)
  print(stampToTime(a1))
  a2 = get_time_stamp13()
  print(a2)
  print(stampToTime(a2))

补充拓展:关于python生成唯一Id的几种方法小结

# coding:utf-8
import random
def createRandomString(len):
  print ('wet'.center(10,'*'))
  raw = ""
  range1 = range(58, 65) # between 0~9 and A~Z
  range2 = range(91, 97) # between A~Z and a~z

  i = 0
  while i < len:
    seed = random.randint(48, 122)
    if ((seed in range1) or (seed in range2)):
      continue;
    raw += chr(seed);
    i += 1
  # print(raw)
  return raw

print createRandomString(20)

print ("test".center(20,"-"))
#! coding:utf-8
import uuid
print u"uuid1 生成基于计算机主机ID和当前时间的UUID"
print uuid.uuid1() # UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

print u"\nuuid3 基于命名空间和一个字符的MD5加密的UUID"
print uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') #UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

print u"\nuuid4 随机生成一个UUID"
print uuid.uuid4()
#'16fd2706-8baf-433b-82eb-8c7fada847da'

print u"\nuuid5 基于命名空间和一个字符的SHA-1加密的UUID"
uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') #UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

print u"\n根据十六进制字符生成UUID"
x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
print u"转换成十六进制的UUID表现字符"
print str(x)    # '00010203-0405-0607-0809-0a0b0c0d0e0f'''

以上这篇python生成13位或16位时间戳以及反向解析时间戳的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论