No matter which programming language, time is certainly a very important part. Today, let's see how Python handles time and python timing tasks.
Note: This article talks about the implementation of Python 3, which is slightly different in Python 2.
1. Calculate the dates of tomorrow and yesterday
#! /usr/bin/env python #coding=utf-8 # Get today, yesterday and tomorrow's dates # Introducing datetime module import datetime #Calculate today's time today = datetime.date.today() #Count yesterday's time yesterday = today - datetime.timedelta(days = 1) #Calculate tomorrow's time tomorrow = today + datetime.timedelta(days = 1) #Print these three times print(yesterday, today, tomorrow)
2. Calculate the last time
Method 1:
#! /usr/bin/env python #coding=utf-8 # Calculate last time #Introducing two modules of datetime and calendar import datetime,calendar last_friday = datetime.date.today() oneday = datetime.timedelta(days = 1) while last_friday.weekday() != calendar.FRIDAY: last_friday -= oneday print(last_friday.strftime('%A, %d-%b-%Y'))
Method 2: find the last Friday with the help of modular operation
#! /usr/bin/env python #coding=utf-8 # With the help of modular operation, the number of days to be subtracted can be calculated once, and the last Friday can be calculated. #It also introduces two modules, datetime and calendar. import datetime import calendar today = datetime.date.today() target_day = calendar.FRIDAY this_day = today.weekday() delta_to_target = (this_day - target_day) % 7 last_friday = today - datetime.timedelta(days = delta_to_target) print(last_friday.strftime("%d-%b-%Y"))
3. Calculate the total playing time of songs
#! /usr/bin/env python #coding=utf-8 # Get the sum of playing time of all songs in a list import datetime def total_timer(times): td = datetime.timedelta(0) duration = sum([datetime.timedelta(minutes = m, seconds = s) for m, s in times], td) return duration times1 = [(2, 36), (3, 35), (3, 45), ] times2 = [(3, 0), (5, 13), (4, 12), (1, 10), ] assert total_timer(times1) == datetime.timedelta(0, 596) assert total_timer(times2) == datetime.timedelta(0, 815) print("Tests passed.\n" "First test total: %s\n" "Second test total: %s" % (total_timer(times1), total_timer(times2))) //When you are learning python, you will surely encounter many problems and the pursuit of new technology. Here is our Python resource sharing autumn skirt: 855408893 has an installation package and learning video materials. This is the gathering place for Python learners. You are welcome to share some learning methods and small details that need attention every day.
4. Execute a command repeatedly
#! /usr/bin/env python #coding=utf-8 # Execute a command at the required interval import time, os def re_exe(cmd, inc = 60): while True: os.system(cmd); time.sleep(inc) re_exe("echo %time%", 5)
5. Scheduled tasks
#! /usr/bin/env python #coding=utf-8 #Three modules need to be introduced here import time, os, sched # The first parameter determines the time of the task, and returns the number of seconds from a specific time to the present. # The second parameter measures time in a human way. schedule = sched.scheduler(time.time, time.sleep) def perform_command(cmd, inc): os.system(cmd) def timming_exe(cmd, inc = 60): # enter is used to schedule the occurrence time of an event. It starts at the nth second from now on. schedule.enter(inc, 0, perform_command, (cmd, inc)) # Keep running until the scheduled time queue becomes empty schedule.run() print("show time after 10 seconds:") timming_exe("echo %time%", 10)
6. Using sched to implement periodic call
#! /usr/bin/env python #coding=utf-8 import time, os, sched # The first parameter determines the time of the task, and returns the number of seconds from a specific time to the present. # The second parameter measures time in a human way. schedule = sched.scheduler(time.time, time.sleep) def perform_command(cmd, inc): # Schedule yourself to run again after inc seconds, i.e. periodic operation schedule.enter(inc, 0, perform_command, (cmd, inc)) os.system(cmd) def timming_exe(cmd, inc = 60): # enter is used to schedule the occurrence time of an event. It starts at the nth second from now on. schedule.enter(inc, 0, perform_command, (cmd, inc)) # Keep running until the scheduled time queue becomes empty schedule.run() print("show time after 10 seconds:") timming_exe("echo %time%", 10)