Using python to obtain time is often the top priority of automated office. For example, when filling in the freight bill form, automatically obtaining the current time can simplify the operation of manual entry and reduce the risk of error, or when performing regular When writing scripts, automatic acquisition of time can often free hands. Therefore, it is necessary to make a complete supplement to the operation of time processing.
1. Get the current time
import datetime
current_time = datetime.datetime.now()
print(current_time)
operation result:
2023-04-24 09:27:34.255374
2. Format time
import datetime
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
operation result:
2023-04-24 09:29:20
3. Time interval
import datetime
current_time = datetime.datetime.now()
time_interval = current_time - datetime.datetime.now()
print(time_interval)
operation result:
0:00:00
4. Time frame
import datetime
current_time = datetime.datetime.now()
time_range = datetime.datetime(current_time.year, current_time.month, current_time.day) - datetime.datetime(current_time.year, current_time.month, current_time.day)
print(time_range)
operation result:
0:00:00
5. Comparison of date and time
import datetime
current_time = datetime.datetime.now()
earlier_time = current_time - datetime.timedelta(days=1)
later_time = current_time + datetime.timedelta(days=1)
print(earlier_time)
print(later_time)
operation result:
2023-04-23 09:31:54.759432
2023-04-25 09:31:54.759432
6. Time processing case
import json
import requests
import datetime
import urllib.parse
import traceback
now = datetime.datetime.now()+datetime.timedelta(days = 1)
today = now.strftime("%Y-%m-%d") + "T00:00:00+08:00"
print(now)
print(today)
operation result:
2023-04-25 09:36:15.569446
2023-04-25T00:00:00+08:00