Common calculations in python on time and date functions are summarized as of time and datatime

  • 2020-04-02 09:50:52
  • OfStack

1. Two ways to get the current time:


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

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


last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
print last

3. Get the time difference (the unit of time difference is seconds, which is often used to calculate the running time of the program)


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

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


d1 = datetime.datetime.now()
d3 = d1 + datetime.timedelta(hours=10)
d3.ctime()

The commonly used classes are datetime and timedelta. They can add and subtract from each other. Each class has some methods and properties to view specific values, such as datetime: day, hour, weekday(), etc. Timedelta can be viewed as: days, seconds, etc.  

5. Time and date formatting symbols in python:

The two-digit year of %y is (00-99).
The year of %Y with four digits (000-9999)
Month (01-12)
%d day of the month (0-31)
%H 24-hour hours (0-23)
%I 12 hours (01-12)
%M minutes (00=59)
%S seconds (00-59)

%a locally simplified week name
%A local full week name
%b local simplified month name
%B local full month name
%c local corresponding date and time representations
%j one day in the year (001-366)
Local A.M. or P.M. equivalent of %p
The number of weeks of the year (00-53) Sunday is the beginning of the week
W week (0-6), Sunday is the beginning of the week
The number of weeks in a year (00-53) Monday is the beginning of the week
%x is represented locally by the corresponding date
%X local corresponding time representation
%Z the name of the current time zone
The %% % sign itself


Related articles: