Getting started with Python: Common modules-time & datetime modules

Source: Internet
Author: User
Tags locale month name time interval timedelta

In Python, common modules related to time processing are: Time,datetime,calendar (seldom used)

First, in Python, there are usually several ways to represent time:

    1. Time stamp
    2. Formatted time string
    3. Tuple (Struct_time) a total of nine elements

Ii. definition of several

UTC (coordinated Universal time, world co-ordination) is GMT, world standard Time. In China for Utc+8. DST (daylight saving time) is daylight saving time.

Timestamp (timestamp): Typically, a timestamp represents an offset that is calculated in seconds, starting January 1, 1970 00:00:00. We run "type (Time.time ())" and return the float type.

Tuple (struct_time) mode: There are 9 elements in the Struct_time tuple, and the functions that return struct_time are mainly gmtime (), localtime (), Strptime (). Several elements in this way tuple are listed below:

Index (Index)    property (Attribute)    value 0     tm_year (year)                 1     tm_mon (month)             1-122     tm_mday (Sun)                 1-313     Tm_hour (time)                 0-234     tm_min (min)             0-595 tm_sec     (sec)             0-616     tm_ Wday (Weekday)            0-6 (0 = Sunday) 7     tm_yday (Day of the year)    1-3668     tm_isdst (Daylight saving Time)            by default-1
method of the time module
  • Time.localtime ([secs]): Converts a timestamp to the struct_time of the current time zone. The secs parameter is not provided, whichever is the current time.
  • Time.gmtime ([secs]): Similar to the LocalTime () method, the Gmtime () method is the struct_time of converting a timestamp to the UTC time zone (0 o'clock Zone).
  • Time.time (): Returns the timestamp of the current time.
  • Time.mktime (t): Converts a struct_time to a timestamp.
  • Time.sleep (secs): Thread delays the specified time run. Unit is seconds.
  • Time.asctime ([t]): A tuple or struct_time representing time is represented in this form: ' Sun Oct 1 12:04:38 2017 '. If there are no parameters, Time.localtime () will be passed in as a parameter.
  • Time.ctime ([secs]): Converts a timestamp (floating point number in seconds) to the form of Time.asctime (). If the parameter is not given or is none, the default Time.time () is the parameter. Its function is equivalent to Time.asctime (time.localtime (secs)).
  • Time.strftime (format[, T]): Converts a tuple or struct_time that represents time (such as returned by Time.localtime () and Time.gmtime ()) to a formatted time string. If T is not specified, the Time.localtime () is passed in.

    • Example: Time.strftime ("%y-%m-%d%x", Time.localtime ()) #输出 ' 2017-10-01 12:14:23 '
  • Time.strptime (string[, format]): Converts a formatted time string to Struct_time. In fact it is inverse operation with strftime ().

Example: Print (Time.strptime ("2018-05-22 22:56", "%y-%m-%d%h:%m"))

Output:

Time.struct_time (tm_year=2018, tm_mon=5, tm_mday=22, tm_hour=22, tm_min=56, tm_sec=0, Tm_wday=1, tm_yday=142, TM_ISDST =-1)

  

String to time format corresponding table
meaning Notes
%a Locale ' s abbreviated weekday name.
%A Locale ' s full weekday name.
%b Locale ' s abbreviated month name.
%B Locale ' s full month name.
%c Locale ' s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale ' s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the Week) as a decimal number [00,53]. A New year preceding the first Sunday is considered to is in week 0. (3)
%w Weekday as a decimal number [0 (Sunday), 6].
%W Week number of the year (Monday as the first day of the Week) as a decimal number [00,53]. A New year preceding the first Monday is considered to is in week 0. (3)
%x Locale ' s appropriate date representation.
%X Locale ' s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z Time zone offset indicating a positive or negative time difference from utc/gmt of the form +hhmm or-hhmm, where H repres Ents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].
%Z Time zone name (no characters if no time zone exists).
%%

Finally, in order to easily remember the conversion relationship, such as:

datetime Module

The interface of the DateTime module is more intuitive and easier to invoke than the time module

The DateTime module defines the following classes:

    • Datetime.date: A class that represents a date. The commonly used attributes are year, month and day;
    • Datetime.time: A class that represents time. The commonly used properties are hour, minute, second, microsecond;
    • Datetime.datetime: Represents the DateTime.
    • Datetime.timedelta: Represents the time interval, which is the length between two points in time.
    • Datetime.tzinfo: Related information about the time zone. (This class is not discussed in detail here, and interested children's shoes can refer to the Python manual)

The method we need to remember is only the following:

    1. D=datetime.datetime.now () returns the current datetime date type
Print (D.timestamp ()) print (D.today ()) print (d.year) print (D.timetuple ())

2. Print (D.fromtimestamp (322222)) # Convert a timestamp to a datetime date type

3. Time arithmetic

    • Print (Datetime.datetime.now () + Datetime.timedelta (5))  # Current time + 5 days
      Print (Datetime.datetime.now () + Datetime.timedelta (hours=5)) # Current time + 5 hours

        

4. Time Replacement

Print (D.replace (year=2009, month=2, day=20))

  

Getting started with Python: Common modules-time & datetime modules

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.