Python time manipulation examples and time formatting parameter summaries

  • 2020-04-02 13:36:35
  • OfStack

1. Method of taking the specific time:


#!/usr/bin/python   
import time  
# Take the current time from one day ago    
time.strftime('%Y-%m-%d %T',time.localtime(time.time()-24*60*60))   
# take 15 Current specific time days ago    
time.strftime('%Y-%m-%d %T',time.localtime(time.time()-15*24*60*60))   
# take 15 Days before the current specific time 2 hours    
time.strftime('%Y-%m-%d %T',time.localtime(time.time()-15*24*60*60-2*60*60))

2. The method of taking the specific time in the future:

#!/usr/bin/python   
import time  

# Take the current time after one day    
time.strftime('%Y-%m-%d %T',time.localtime(time.time()+24*60*60))   

# take 20 The current specific time of the day after tomorrow    
time.strftime('%Y-%m-%d %T',time.localtime(time.time()+20*24*60*60))   

# take 20 Days before the current specific time 2 hours    
time.strftime('%Y-%m-%d %T',time.localtime(time.time()+20*24*60*60-2*60*60)) 

3. Only take the specific value of a unit of time in the past and future:


#!/usr/bin/python   
import time  

# Take the month before    
time.localtime()[1]-1   

# Take the year before    
time.localtime()[0]-1   

# Take the month after two months    
time.localtime()[1]+2  

Strftime () format command:


%a  Days of the week    
%A  The full name of the day of the week    
%b  Short for month    
%B  The full name of the month    
%c  A time series of standard dates    
%C  The last two digits of the year    
%d  The day of the month in decimal notation    
%D  month / day / years    
%e  In a two-character field, the decimal number for the day of the month    
%F  years - month - day    
%g  The last two digits of the year, using the week-based year    
%G  Year points, using week-based years    
%h  The name of the month in short    
%H 24 Hours by the hour    
%I 12 Hours by the hour    
%j  The number of days of the year in decimal notation    
%m  A decimal month    
%M  The number of minutes in ten minutes    
%n  New line character    
%p  The local AM or PM Equivalent display of    
%r 12 Hours of time    
%R  Display hours and minutes: hh:mm   
%S  The number of seconds in decimal    
%t  Horizontal tabs    
%T  Display time: hh:mm:ss   
%u  The first day of the week is Monday   (the value from 0 to 6 , Monday for 0 )    
%U  Week 1 of the year, make Sunday your first day 0 to 53 )    
%V  For the week of the year, use the week-based year    
%w  Decimal represents the day of the week (value from 0 to 6 On Sunday 0 )    
%W  Week of the year, make Monday your first day 0 to 53 )    
%x  Standard date string    
%X  Standard time series    
%y  Decimal year without century (value from 0 to 99 )    
%Y  Ten years with the century part    
%z . %Z  Time zone name, returns a null character if the time zone name cannot be obtained.    
%%  percent 


Related articles: