SoFunction
Updated on 2024-11-18

Example usage of the time and datetime modules in Python

time module method:
():Get the timestamp of the current time

(): accepts a timestamp and converts it to a tuple of the current time. Passing in () as an argument by default if you don't give it a parameter

():
indexing causality hidden meaning
0 tm_year surname Nian
1 tm_mon moon
2 tm_mday date
3 tm_hour hour
4 tm_min ingredient
5 tm_sec unit of angle or arc equivalent one sixtieth of a degree
6 tm_wday Day of the week
7 tm_yday The first days of the year
8 tm_isdst daylight saving time
  • (): the opposite of (), it converts a time tuple into a timestamp (this must be given a parameter)
  • (): represents a time tuple as: "Sun Jul 28 03:35:26 2013", if you don't give it a parameter, it will pass () as a parameter.
  • (): converts a timestamp to a () expression, which is passed as a parameter if no parameter is given.
  • (): convert a timestamp to a time tuple in UTC+0 time zone (China should be +8 time zone, a difference of 8 hours), if you don't give any parameter, you will pass () as a parameter by default.
  • (format,()): convert a time tuple to a formatted time character, if you don't give a time tuple parameter you will pass () as a parameter.

For example, the time format in the web log is ('%d/%b/%Y:%X').

Returns results:

Sun Jul 28 04:37:38 2013

format:

causality specification hidden meaning Range of values (format)
particular year %y Remove the year of the century 00-99
%Y Complete year
%j The first days of the year 001-366
months %m months January 12
%b Local simplification of the name of the month Abbreviated English months
%B Name of the full local month Full English month
dates %d Days of the month January 31st
hourly %H Hour of the day (24-hour day) 00-23
%l Hour(s) (12-hour clock) “01-12”
minutes %M minutes 00-59
unit of angle or arc equivalent one sixtieth of a degree %S unit of angle or arc equivalent one sixtieth of a degree 00-59
last week %U Number of weeks in a year (counting from Sunday) 00-53
%W Number of weeks in a year (counting from Monday)
%w Days of the week 0-6
time zones %Z China: should be GMT+8 (China Standard Time) Literacy
(sth. or sb) else %x Local corresponding date DD/MM/YYYY
%X local time stamp Hour:Minute:Second
%c Detailed date and time Day/Month/Year Hour:minute:second
%% '%' character '%' character
%p The local am or pm equivalent AM    or    PM

(stringtime,format): converts a time string into an array of times according to the specified formatters.
Example:
('28/Jul/2013:04:33:29', '%d/%b/%Y:%X')

Returns results:

Copy Code The code is as follows.
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=28, tm_hour=4, tm_min=33, tm_sec=29, tm_wday=6, tm_yday=209, tm_isdst=-1)

(): return to the processor clock time, generally used for performance testing and benchmarking, etc., because they reflect the actual time used by the program, usually do not use this.

():Delay running for the specified time in seconds.

import time
print () # Print timestamps
print ()# Print local time tuple
print ()# Promise a time tuple in the UTC+0 time zone.
print ()#Print asctime formatted time
print (())# Convert time tuples to timestamps
print ()# Print formatting time
print ('%d/%b/%Y:%X')# Print the time format in the specified format
# Translate a time string and its format into a time tuple
print ('28/Jul/2013:04:33:29', '%d/%b/%Y:%X')
print '%0.5f'%() # Print processor time
for i in range(100000): 
 pass
print '%0.5f'%()# Print processor time

Take a look at the results:

[root@localhost ~]# python 
1364028568.55
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=23, tm_hour=4, tm_min=49, tm_sec=28, tm_wday=5, tm_yday=82, tm_isdst=1)
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=23, tm_hour=8, tm_min=49, tm_sec=28, tm_wday=5, tm_yday=82, tm_isdst=0)
Sat Mar 23 04:49:28 2013
1364028568.0
Sat Mar 23 04:49:28 2013
23/Mar/2013:04:49:28
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=28, tm_hour=4, tm_min=33, tm_sec=29, tm_wday=6, tm_yday=209, tm_isdst=-1)
0.02000
0.03000

datetime module
():Generate a time object. This time can be set by us, default are 0 (this class is only for time)

#coding:utf-8
import datetime
print ()
t = (1, 3, 5, 25)
print t
print  #time
print  # points
print  # seconds
print  # milliseconds
print  # End of day
print  # Start of the day

Execute it:

00:00:00
01:03:05.000025

23:59:59.999999
00:00:00

():Generate a date object. This date is to be set by us, (this class is only for dates)

#coding:utf-8
import datetime
#Set the date
t = (2013, 2, 3)
# Print the sum tuple of the set date
print ()# Date tuple
print t
print  # year
print  #Month
print  #Day
# Get today's date
today = ()
print today
print ()# This prints to the millisecond
# Get a tuple of today's date
t1 = ()
print t1
# Print to ctime format (() format)
#'%a %b %d %H:%M:%S %Y'
print ()
print ()

running result

time.struct_time(tm_year=2013, tm_mon=2, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=34, tm_isdst=-1)
2013-02-03
2013
2
3
2013-07-28
2013-07-28 20:13:25.942000
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=209, tm_isdst=-1)
Sun Feb 3 00:00:00 2013
Sun Jul 28 00:00:00 2013

(): This class is used to do arithmetic operations on time.
(date,time):This is used to combine the date and time of the

#coding:utf-8
import datetime
#Print: milliseconds to weeks representation = convert to seconds (total_seconds())
for i in [(milliseconds=1), #1 millisecond
  (seconds=1), #1 second
  (minutes=1), #1 minute
  (hours=1), #1 hour.
  (days=1), #1 day
  (weeks=1)]:#11 weeks
 #print i + ':' + i.total_seconds()
 print '%s = %s seconds'%(i,i.total_seconds())
print
print '~' * 20 + 'I'm the dividing line' + '~' * 20
print 'Calculate the addition and subtraction of time 。。。。。。。。。'
a = ()
print 'The time is now:'
print a
print 'After adding 5 hours it becomes:'
b = a + (hours=5)
print b
print ' After adding a week it becomes: '
c = a + (weeks=1)
print c
print ' Minus one week becomes: '
d = a - (weeks=1)
print d
print 'Calculate how long the 2 times differ'
print '%s minus %s'%(b, a)
print 'Equals:%s'%(b - a)
print '%s minus %s'%(a, d)
print 'Equals:%s'%(a - d)
print
print '~' * 20 + 'I'm the dividing line' + '~' * 20
print 'Compare 2 times:'
print 'Comparing the same day and a week ago'
print a > d
print 'False if compare d > a'
print
print '~' * 20 + 'I'm the dividing line' + '~' * 20
print 'The columns above all separate date and time, now let's combine them freely'
print 'Suppose the time we want is: 2014-01-05 13:14:25'
t = (13, 14, 25)
d = (2014, 01, 05)
print (d, t)


Print as:

0:00:00.001000 = 0.001 seconds
0:00:01 = 1.0 seconds
0:01:00 = 60.0 seconds
1:00:00 = 3600.0 seconds
1 day, 0:00:00 = 86400.0 seconds
7 days, 0:00:00 = 604800.0 seconds

Calculating addition and subtraction of time 。。。。。。。。。

The time is now:
2013-07-28 21:34:33.531000
plus5After hours it becomes:
2013-07-29 02:34:33.531000
plus一周之后变成:
2013-08-04 21:34:33.531000
One week after the loss of the:
2013-07-21 21:34:33.531000
count2What's the time difference?
2013-07-29 02:34:33.531000take2013-07-28 21:34:33.531000
be tantamount to:5:00:00
2013-07-28 21:34:33.531000take2013-07-21 21:34:33.531000
be tantamount to:7 days, 0:00:00

comparisons2time:
comparisons当天和一周前的
True
如果comparisonsd > a and then returnsFalse

The columns above all separate the date from the time,Now let's combine them freely.
Suppose the time we want is:2014-01-05 13:14:25
2014-01-05 13:14:25