Interconversion of time types in Python

The 3-in-3 representation format of the time, and the conversion between them:

In Python, there are usually three ways to represent time: timestamp, tuple (struct_time), formatted time string:

(1) Timestamp: Generally speaking, a timestamp represents an offset calculated in seconds from 00:00:00 on January 1, 1970. We run "type(time.time())" and it returns a float.

(2) Formatted time string (Format String): '2018-04-18'

(3) Tuple (struct_time): There are 9 elements in the struct_time tuple: (year, month, day, hour, minute, second, week of the year, day of the year, etc.)

Uses: Timestamps are times that computers can recognize; time strings are times that people can understand; tuples are used to manipulate time



Convert:

1. Timestamp --> Formatting --> String

_now = time.time() # timestamp

struct_time = time.localtime(_now) # Convert timestamp to formatted time

time.strftime("%Y-%m-%d %X", struct_time)    # 2018-04-21 22:44:53

1. String --> Formatting --> Timestamp

str_time = '2018-04-18 08:00:00'

struct_time2 = time.strptime(str_time,'%Y-%m-%d %H:%M:%S') # string to format

timestamp = time.mktime(struct_time2) # format to timestamp
# =======The above is the time module, and the bottom is the datetime module ===========================

import datetime

# 1. Timestamp-->Formatting-->Character

timestamp1 = 1509636585.0   # 2018-04-21 23:47:02.886948

# Convert timestamp to formatted (datetime type) time
struct_time = datetime.datetime.fromtimestamp(1509636585.0)   # 类型:<class 'datetime.datetime'>

# Format to string type
str_time = datetime.datetime.strftime(struct_time,'%Y-%m-%d %H:%M:%S')   # 2017-11-02 23:29:45

# 2. Character-->Formatting--> Timestamp
str_time1 = '2017-11-02 23:29:45'

# string --> format
struct_time = datetime.datetime.strptime(str_time1,'%Y-%m-%d %H:%M:%S')

# Formatting-->Timestamp
time_stamp = time.mktime(struct_time.timetuple())  # 1509636585.0


Calculation between time

# interval between times
# 1. Time delay, advance calculation
now =datetime.datetime.now()

# this time tomorrow
tomorrow_now = now + datetime.timedelta(days=1)

# this time yesterday
yes_now = now + datetime.timedelta(days=-1)

# 2. Difference between two times
days = (tomorrow_now - yes_now).days   # 2


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325406302&siteId=291194637