Analysis of the usage examples of the time and datetime modules in Python

Source: Internet
Author: User
Tags time zones timedelta
This article mainly introduces the usage examples of the time module and datetime module in Python. it mainly demonstrates the printing and calculation of time and date. For more information, see Time Module method:

Time. time (): Get the timestamp of the current time

Time. localtime (): Receives a timestamp and converts it to a tuples of the current time. If no parameter is specified, time. time () is input as the parameter by default.

Time. localtime ():
Index Attribute Description
0 Tm_year Year
1 Tm_mon Month
2 Tm_mday Day
3 Tm_hour Hour
4 Tm_min Minute
5 Tm_sec Seconds
6 Tm_wday Day of the week
7 Tm_yday Day of the year
8 Tm_isdst Daylight saving time
  • Time. mktime (): opposite to time. localtime (), it converts a time tuple to a timestamp (this must be a parameter)

  • Time. asctime (): indicates a time tuple in the format of "Sun Jul 28 03:35:26 2013". If no parameter is specified, time. localtime () is passed as the parameter by default.

  • Time. ctime (): converts a timestamp to the expression format of time. asctime (). If no parameter is set, time. time () is passed as the parameter by default.

  • Time. gmtime (): converts a timestamp to a timestamp in UTC + 0 (China should be a + 8 time zone, with a difference of 8 hours, if no parameter is specified, the time is set by default. time () is passed as a parameter

  • Time. strftime (format, time. localtime (): converts a time tuple to a formatted time character. if the time tuple parameter is not provided, the time is set by default. localtime () is passed as a parameter

For example, the time format in the web log is time. strftime ('% d/% B/% Y: % x ')

Returned results:

Sun Jul 28 04:37:38 2013

Format:

Attribute Format Description Value range (format)
Year % Y Remove the year of the century 00-99
% Y Complete year
% J Day of the year 001-366
Month % M Month January 12
% B Name of the local simplified month Abbreviated month
% B Name of the complete local month Full English month
Date % D The day of the month January 31
Hours % H The hour of the day (in 24-hour format) 00-23
% L Hour (in 12-hour format) "01-12"
Minutes % M Minutes 00-59
Seconds % S Seconds 00-59
Week % U The number of weeks in a year (from Sunday) 00-53
% W The number of weeks in a year (starting from Monday)
% W The day of a week 0-6
Time zone % Z China: it should be GMT + 8 (China Standard Time) Please read the literacy
Others % X Local date Day/month/year
% X Local photo printing time Hour: minute: Second
% C Detailed date and time Day/month/year hour: minute: Second
% '%' Character '%' Character
% P The identifier of the local am or pm. AM or PM


Time. strptime (stringtime, format): converts a time string to an array of time based on the specified formatting character,
For example:

time.strptime('28/Jul/2013:04:33:29', '%d/%b/%Y:%X')

Returned results:

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)

Time. clock (): return the processor clock time, which is generally used for performance testing and benchmark testing. because they reflect the actual time used by the program, this is usually not used.

Time. sleep (): delay the specified time, in seconds

Import timeprint time. time () # print the timestamp print time. localtime () # print the local time tuples print time. gmtime () # time tuples that promise UTC + 0 time zones print time. ctime () # print asctime format time print time. mktime (time. localtime () # Convert the time tuples to the print time stamp. asctime () # print the formatting time print time. strftime ('% d/% B/% Y: % X') # print the time format in the specified format # translate the time string and its format into print time. strptime ('28/Jul/2013: 04: 33: 29', '% d/% B/% Y: % X') print' % 0.5f' % time. clock () # print the processor time for I in range (100000): passprint '% 0.5f' % time. clock () # print the processor time

Let's take a look at the results:

[root@localhost ~]# python time1.py

1364028568.55time.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 20131364028568.0Sat Mar 23 04:49:28 201323/Mar/2013:04:49:28time.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.020000.03000


Datetime module
Datetime. time (): generates a time object. This time can be set by US. The default value is 0 (this class only applies to time)

# Coding: utf-8import datetimeprint datetime. time () t = datetime. time (1, 3, 5, 25) print tprint t. hour # print t. minute # minute print t. second # seconds print t. microsecond # print datetime in milliseconds. time. max # end time of a day print datetime. time. min # start time of a day

Run the following command:

00:00:0001:03:05.00002523:59:59.99999900:00:00

Datetime. date (): generate a date object. This date should be set by us (this class is only for date)

# Coding: utf-8import datetime # set date t = datetime. date (2013, 2, 3) # print the set date and metadata print t. timetuple () # Date tuples print tprint t. year # print t. month # monthly print t. day # get today's date today = datetime. date. today () print todayprint datetime. datetime. now () # print it to the millisecond level # obtain the TKEY t1 = today of the current date. timetuple () print t1 # print to ctime format (time. ctime () format) # '% a % B % d % H: % M: % S % Y' print t. ctime () print today. ctime ()

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-032013232013-07-282013-07-28 20:13:25.942000time.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 2013Sun Jul 28 00:00:00 2013

Datetime. timedelta (): This class is used to calculate the time.
Datetime. datetime. combine (date, time): used to combine the date and time

# Coding: utf-8import datetime # Print: representation format from milliseconds to weeks = converted to seconds (total_seconds () for I in [datetime. timedelta (milliseconds = 1), #1 millisecond datetime. timedelta (seconds = 1), #1 second datetime. timedelta (minutes = 1), #1 minute datetime. timedelta (hours = 1), #1 hour datetime. timedelta (days = 1), #1 day datetime. timedelta (weeks = 1)]: #11 weeks # print I + ':' + I. total_seconds () print '% s = % s seconds' % (I, I. total_seconds () printprint '~ '* 20 +' I am a split line' + '~ '* 20 print' calculates the addition and subtraction of time ......... 'A = datetime. datetime. now () print 'current time is: 'Print aprint' plus 5 hours and then changed to: 'B = a + datetime. timedelta (hours = 5) print bprint after a week is added to: 'C = a + datetime. timedelta (weeks = 1) print cprint 'is changed to: 'd = a-datetime after a week. timedelta (weeks = 1) print dprint calculate the difference between the two times: 'Print '% s minus % s' % (B, a) print' equals: % s' % (B-a) print '% s minus % s' % (a, d) print' equals to: % s' % (a-d) printprint '~ '* 20 +' I am a split line' + '~ '* 20 print' compares two times: 'Print 'compares 'print a> dprint' of the current day and a week ago. if d> a is compared, False 'printprint '~ is returned '~ '* 20 +' I am a split line' + '~ The columns above '* 20 print' separate the date and time. now we can combine them freely with 'print'. Suppose we want the time: 13:14:25't = datetime. time (13, 14, 25) d = datetime. date (2014, 01, 05) print datetime. datetime. combine (d, t)


Print:

0:00:00.001000 = 0.001 seconds0:00:01 = 1.0 seconds0:01:00 = 60.0 seconds1:00:00 = 3600.0 seconds1 day, 0:00:00 = 86400.0 seconds7 days, 0:00:00 = 604800.0 seconds

Calculate the addition and subtraction of time .........

The current time is 21:34:33. 531000 plus 5 hours later: 02:34:33. 531000 plus one week later: 21:34:33. 531000 after a week is subtracted: 21:34:33. 531000 calculate the difference between the two time periods 02:34:33. 531000 minus 21:34:33. 531000 equals: 5: 00: 002013-07-28 21:34:33. 531000 minus 21:34:33. 531000 equals to: 7 days, 0:00:00 compare 2 Time: compare the True values of the current day and a week before. if compare d> a, return False. the column above separates the date from the time, now let's combine them freely. Suppose we want the time: 13:14:25-01-05

For more information about how to use the time module and datetime module in Python, see PHP!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.