SoFunction
Updated on 2024-11-13

Summary of common calculations on time and date functions in python (time and datatime)

1. Two ways to get the current time:

Copy Code The code is as follows.

import datetime,time
now = ("%Y-%m-%d %H:%M:%S")
print now
now = ()
print now

2. Get the date of the last day of the previous month (the first day of the month minus 1 day)

Copy Code The code is as follows.

last = (().year,().month,1)-(1)
print last

3. Get the time difference (time difference in seconds, often used to calculate the time the program runs)

Copy Code The code is as follows.

starttime = ()
#long running
endtime = ()
print (endtime - starttime).seconds

4. Calculate the time 10 hours back from the current time
 

Copy Code The code is as follows.

d1 = ()
d3 = d1 + (hours=10)
()

The two classes that are commonly used on its own are: datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes can view specific values, such as datetime can view: days (day), hours (hour), weekday (weekday ()), etc.; timedelta can view: days (days), seconds (seconds) and so on.

The time-date formatting symbols in the

%y Two-digit year indication (00-99)
%Y Four-digit year indication (000-9999)
%m Month (01-12)
%d Day of the month (0-31)
%H 24-hour clock hours (0-23)
%I 12-hour hours (01-12)
%M minutes (00=59)
%S seconds (00-59)

%a Local simplified weekly name
%A Local full week name
%b Local simplified name of the month
%B Local full month name
%c Local corresponding date representation and time representation
%j Day of the year (001-366)
%p Local. or . Equivalents of
%U Number of weeks in a year (00-53) Sunday is the start of the week
%w Week (0-6), Sunday is the start of the week
%W Number of weeks in a year (00-53) Monday is the start of the week
%x Local representation of the corresponding date
%X Local corresponding time representation
%Z Name of the current time zone
%% % sign itself