Python Time module hours & datetime & Calendar

Source: Internet
Author: User
Tags julian day local time month name string format timedelta

I. INTRODUCTION

Python provides many ways to handle dates and times, and converting date formats is a common feature.

Time tuples: Many Python functions use a single element to assemble 9 sets of digital processing time.

  

Python format symbols in time Date:

%y Two-digit year represents (00-99)%y four-digit year (000-9999)%m month (01-12) Day (0-31)%H 24-hour hours (0-23)%I 12-hour hours (01-12)%M minutes (00=59)%s seconds (00-59)%a Local simplified week name%a Local full week name%b Local simplified month name%b Local full month name%c local corresponding date representation and time representation%j One day of the year (001-366)%p local a.m. or p.m. the number of weeks in the year (00-53) Sunday for the beginning of the week%w Weeks (0-6), Sunday for the beginning of the week%w the week of the Year (00-53) Monday for the beginning of the week%x Local corresponding date indicates%x local corresponding time represents%z current time zone name%% number itself
Two. Time module

Time-related operations, time has three kinds of means:

    • Timestamp after January 1, 1970 seconds, i.e.: Time.time ()
    • Formatted string 2014-11-11 11:11, i.e.: Time.strftime ('%y-%m-%d ')
    • Structured time tuples include: year, day, week, etc. time.struct_time is: time.localtime ()

Time.time ()

Returns the timestamp of the current time (the number of floating-point seconds elapsed after the 1970 era). Timestamp units are best suited for date operations. But the dates before 1970 cannot be expressed in this way. Too far away from the date, UNIX and Windows only support to 2038 years. >>> Import time>>> Print (Time.time ()) 1459999336.1963577

Time.mktime (Tupletime)

Accepts the time tuple and returns the time suffix (the number of floating-point seconds elapsed after the 1970 era). The Python time.mktime () function performs the opposite of Gmtime (), localtime (), which receives the Struct_time object as a parameter and returns a floating-point number that represents the time in seconds. If the value entered is not a valid time, overflowerror or valueerror will be triggered. #!/usr/bin/python3import Timet = (2, 3, 1, 0) secs = time.mktime (t) print ("Time.mktime (t):%f"%
   secs) Print ("Asctime (localtime (secs):%s"% Time.asctime (time.localtime (secs))) The output of the above instance is: Time.mktime (t): 1455699818.000000asctime (localtime (secs)): Wed Feb 17 17:03:38 2016

Time.gmtime ([secs])

Receives the time suffix (the number of floating-point seconds elapsed after the 1970 era) and returns the time-tuple T in Greenwich Astronomical time. Note: T.TM_ISDST is always 0>>> import time>>> print ("Gmtime:", Time.gmtime (1455508609.34375)) Gmtime: Time.struct_time (tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst= 0)

Time.localtime ([secs])

The Receive time suffix (the number of floating-point seconds after the 1970 era) and the time-of-day tuple T (t.tm_isdst 0 or 1, depending on whether the local time is daylight saving). >>> Import time>>> Print ("LocalTime ():", Time.localtime (1455508609.34375)) localtime ():  Time.struct_time (tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, TM_ISDST =0)

Time.mktime (Tupletime)

Accepts the time tuple and returns the time suffix (the number of floating-point seconds elapsed after the 1970 era). The Python time Mktime () function performs the opposite of Gmtime (), localtime (), which receives the Struct_time object as a parameter and returns a floating-point number that represents the times in seconds. If the value entered is not a valid time, overflowerror or valueerror will be triggered. #!/usr/bin/python3import Timet = (2, 3, 1, 0) secs = time.mktime (t) print ("Time.mktime (t):%f"%
   secs) Print ("Asctime (localtime (secs):%s"% Time.asctime (time.localtime (secs))) The output of the above instance is: Time.mktime (t): 1455699818.000000asctime (localtime (secs)): Wed Feb 17 17:03:38 2016

Time.strftime (Fmt[,tupletime])

Receives a time tuple and returns the local time as a readable string, formatted as determined by the FMT. >>> Import time>>> Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())) 2016-04-07 11:18:05

Time.strptime (str,fmt= '%a%b%d%h:%m:%s%Y ')

Resolves a time string to a time tuple according to the format of the FMT. >>> import time>>> struct_time = Time.strptime ("Nov", "%d%b%y") >>> print ("Return to tuple:", str Uct_time) returns tuples:  time.struct_time (tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, Tm_wday=3, TM _yday=335, Tm_isdst=-1)

Time.altzone

Time.asctime ([Tupletime])

Accepts a time tuple and returns a read-only string of 24 characters in the form "Tue Dec 11 18:07:14 2008" (December 11, 2008 Tuesday 18:07 14 seconds). >>> Import time>>> t = time.localtime () >>> print ("Time.asctime (t):%s"% time.asctime (t)) Tim E.asctime (t): Thu APR  

Time.clock ()

The number of seconds used to calculate the floating-point count returns the current CPU time. It is more useful than time.time () to measure the time spent on different programs. #!/usr/bin/python3import timedef procedure ():    time.sleep (2.5) # time.clockt0 = Time.clock () procedure () print ( Time.clock ()-T0) # time.timet0 = Time.time () procedure () print (Time.time ()-T0) The result of the above example output is: 5.000000000000143e-052.5020556449890137

Time.ctime ([secs])

function equivalent to Asctime (localtime (secs)), parameter equal to Asctime () >>> Import time>>> print ("Time.ctime ():%s"% Time.ctime ()) Time.ctime (): Thu APR  7 10:51:58 2016

Time.sleep (secs)

Postpone the call thread's run, secs refers to the number of seconds. #!/usr/bin/python3import timeprint ("Start:%s"% time.ctime ()) Time.sleep (5) Print ("End:%s"% time.ctime ())

Time.tzset ()

Re-initializes time-related settings according to the environment variable TZ. Standard TZ environment variable format: STD offset [DST [offset [, Start[/time], End[/time]]] parameter: STD and DST: three or more time abbreviated letters. Passed to Time.tzname.offset: offset from UTC, Format: [+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}. Start[/time], End[/time]: date when DST begins to take effect. The format is m.w.d-, which represents the month, week, and date of the date. W=1 refers to the first week of the month, while W=5 refers to the last week of the month. ' Start ' and ' end ' can be in one of the following formats: Jn: Julian Day N (1 <= n <= 365). Leap Year Day (February 29) is not counted. N: Julian Day (0 <= n <= 365). Leap Year Day (February 29) counts MM.N.D: month, week, and date of the date. W=1 refers to the first week of the month, while W=5 refers to the last week of the month. Time: (optional) When DST begins to take effect (24-hour system). The default value is 02:00 (the local time for the specified time zone). #!/usr/bin/python3import timeimport osos.environ[' TZ '] = ' est+05edt,m4.1.0,m10.5.0 ' Time.tzset () print (time.strftime ('%x%x%Z ')) os.environ[' TZ '] = ' aest-10aedt-11,m10.5.0,m3.5.0 ' Time.tzset () print (Time.strftime ('%x%x%Z ')) The output of the above instance is: 23:25:45 04 /06/16 edt13:25:45 04/07/16 AEST

Time.timezone

The attribute Time.timezone is the number of seconds (>0, Americas; <=0 most of Europe, Asia, and Africa) from Greenwich in the local time zone (daylight saving is not started).

Time.tzname

The Time.tzname property contains a pair of different strings depending on the situation, which is the local time zone name with daylight savings, and No.

Time Change chart:

Three. DateTime module
Print (Datetime.date.today ()) #输出格式 2016-01-26print (Datetime.date.fromtimestamp (Time.time () -864400)) #2016-01-16 Turn timestamp into date format current_time = Datetime.datetime.now () #print (current_time) #输出2016 -01-26 19:04:30.335935print (current_ Time.timetuple ()) #返回struct_time格式  #datetime. replace ([year[, month[, day[, hour[, minute[, second[, microsecond[, Tzinfo]] Print (Current_time.replace (2014,9,12)) #输出2014-09-12 19:06:24.074900, returns the current time, but the specified value will be replaced  str_to_ Date = Datetime.datetime.strptime ("21/11/06 16:30", "%d/%m/%y%h:%m") #将字符串转换成日期格式new_date = Datetime.datetime.now () + Datetime.timedelta (days=10) #比现在加10天new_date = Datetime.datetime.now () + Datetime.timedelta (days=-10) #比现在减10天new_ Date = Datetime.datetime.now () + Datetime.timedelta (hours=-10) #比现在减10小时new_date = Datetime.datetime.now () + Datetime.timedelta (seconds=120) #比现在 +120sprint (new_date)
Four. Calendar Module

The functions of this module are calendar related, Monday is the first day of the week, and Sunday is the last day.

Calendar.calendar (year,w=2,l=1,c=6)

Returns the year calendar of a multi-line string format with a 3-month line with a distance of C. The daily width interval is w characters. The length of each line is 21* w+18+2* C. L is the number of rows per week.

Calendar.firstweekday ()

Returns the settings for the current weekly start date. By default, 0 is returned when the Caendar module is first loaded, which is Monday.

Calendar.isleap (year)

is a leap year that returns true, otherwise false.

Calendar.leapdays (Y1,y2)

Returns the total number of leap years between y1,y2 two.

Calendar.month (year,month,w=2,l=1)

Returns a multi-line string format for year month calendar, two row headings, and one week row. The daily width interval is w characters. The length of each line is 7* w+6. L is the number of rows per week.

Calendar.monthcalendar (Year,month)

Returns a single-level nested list of integers. Each sub-list is loaded with integers representing one weeks. The date of year month is set to 0, and the day of the month is indicated by the day of the week, starting from 1.

Calendar.monthrange (Year,month)

Returns a two integer. The first is the day of the week of the month, and the second is the date code for that month. Day from 0 (Monday) to 6 (Sunday); The month is from 1 to 12.

Calendar.prcal (year,w=2,l=1,c=6)

Equivalent to print Calendar.calendar (year,w,l,c).

Calendar.prmonth (year,month,w=2,l=1)

Equivalent to print Calendar.calendar (year,w,l,c).

Calendar.setfirstweekday (Weekday)

Set the starting date code for the week. 0 (Monday) to 6 (Sunday).

CALENDAR.TIMEGM (Tupletime)

In contrast to Time.gmtime: accepts a time tuple form, returning the time suffix (the number of floating-point seconds elapsed after the 1970 era).

Calendar.weekday (Year,month,day)

Returns the date code for the given date. 0 (Monday) to 6 (Sunday). The month is 1 (January) to 12 (December).

Python Time module hours & datetime & Calendar

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.