Python Time Module timestamp, Time string formatting and Conversion (13-bit timestamp)

Python built-in modules for processing time and timestamp include time, and datetime.

several concepts about timestamps

  • timestamp, offset in seconds starting at 00:00:00 on January 1, 1970.
  • time tuple (struct_time), containing 9 elements. Struct_time (tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=14, tm_min=21, tm_sec=57, tm_wday=6, tm_yday=274, tm_isdst=0)
  • time format string, string form time.

time module is an important function related to timestamp and time

  • time.time() generates the current timestamp in the form of a 10-bit integer floating point number. Strftime () generates a time formatted string based on the time tuple. Strptime () generates time tuples based on time formatting strings. time.strptime() and time.strftime() are interoperable.
  • time.localtime() generates the time tuple for the current time zone based on the timestamp.
  • time.mktime() generates timestamps based on time tuples.

example
A simple example of a timestamp and formatted string is

import time

#生成当前时间的时间戳,只有一个参数即时间戳的位数,默认为10位,输入位数即生成相应位数的时间戳,比如可以生成常用的13位时间戳
def now_to_timestamp(digits = 10):
    time_stamp = time.time()
    digits = 10 ** (digits -10)
    time_stamp = int(round(time_stamp*digits))
    return time_stamp

#将时间戳规范为10位时间戳
def timestamp_to_timestamp10(time_stamp):
    time_stamp = int (time_stamp* (10 ** (10-len(str(time_stamp)))))
    return time_stamp

#将当前时间转换为时间字符串,默认为2017-10-01 13:37:04格式
def now_to_date(format_string="%Y-%m-%d %H:%M:%S"):
    time_stamp = int(time.time())
    time_array = time.localtime(time_stamp)
    str_date = time.strftime(format_string, time_array)
    return str_date

#将10位时间戳转换为时间字符串,默认为2017-10-01 13:37:04格式
def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
    time_array = time.localtime(time_stamp)
    str_date = time.strftime(format_string, time_array)
    return str_date

#将时间字符串转换为10位时间戳,时间字符串默认为2017-10-01 13:37:04格式
def date_to_timestamp(date, format_string="%Y-%m-%d %H:%M:%S"):
    time_array = time.strptime(date, format_string)
    time_stamp = int(time.mktime(time_array))
    return time_stamp

#不同时间格式字符串的转换
def date_style_transfomation(date, format_string1="%Y-%m-%d %H:%M:%S",format_string2="%Y-%m-%d %H-%M-%S"):
    time_array  = time.strptime(date, format_string1)
    str_date = time.strftime(format_string2, time_array)
    return str_date

test

print(now_to_date())
print(timestamp_to_date(1506816572))
print(date_to_timestamp('2017-10-01 08:09:32'))
print(timestamp_to_timestamp10(1506816572546))
print(date_style_transfomation('2017-10-01 08:09:32'))

is

1506836224000
2017-10-01 13:37:04
2017-10-01 08:09:32
1506816572
1506816572
2017-10-01 08-09-32

Read More: