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.

A simple example of a timestamp and formatted string is

import time

def now_to_timestamp(digits = 10):
    time_stamp = time.time()
    digits = 10 ** (digits -10)
    time_stamp = int(round(time_stamp*digits))
    return time_stamp

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


print(date_to_timestamp('2017-10-01 08:09:32'))
print(date_style_transfomation('2017-10-01 08:09:32'))


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

Read More: