Simple use of datetime and time for time series data processing

In time series data, data such as "2020/11/26 0:00:00" is often seen. If you want to use it as a feature variable, it is definitely not realistic to directly put the string in it. One of the conceivable methods One is to take a basic value, and then make a difference, and input the int-type difference as a feature variable into the model.

Since we're using python, that saves us a huge chunk of wheel building. Record the use of datetime here.

1- Use the time module to calculate the seconds between two times:

import datetime
 
start_time = "2020/11/26 0:00:00"
end_time = "2020/11/26 1:00:00"
# 这里的时间格式与文件中的日期格式需对应
start_time1 = datetime.datetime.strptime(start_time , '%Y/%m/%d %H:%M:%S')
end_time1 = datetime.datetime.strptime(end_time , '%Y/%m/%d %H:%M:%S')
seconds = (end_time1 - start_time1).seconds
print(seconds)

2- The date type date is converted to a string str

import datetime
date_i = datetime.datetime.now().date() # 获取当前时刻
str_i = str(date_i)
print(date_i, type(date_i))  # 打印出 2021-01-09 <class 'datetime.date'>
print(str_i, type(str_i))  # 打印出 2021-01-09 <class 'str'>

3- String type str is converted to dateTime type

import datetime

str_i = '2021-01-09 10:52:12'
str_i2 = '2021-01-09'
dateTime_i = datetime.datetime.strptime(str_i, '%Y-%m-%d %H:%M:%S')
dateTime_i2 = datetime.datetime.strptime(str_i2, '%Y-%m-%d')
print(dateTime_i)  # 打印出 2021-01-09 10:52:12
print(dateTime_i2)  # 打印出 2021-01-09 00:00:00

time module

1. Calculate the running time of the program (in seconds)

import time
start = time.time()
time.sleep(4)
end = time.time()

res = end - start
print (round(res,2))

Guess you like

Origin blog.csdn.net/qq_44391957/article/details/122397986