Python Basics-4.1 Time module

Source: Internet
Author: User
Tags month name timedelta

Time & DateTime Module

In the usual code, we often need to deal with time. In Python, the modules related to time processing include: Time,datetime,calendar (seldom used, not spoken), as described below.

Before you begin, here are a few things to note:

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

    1. Time stamp
    2. Formatted time string
    3. The tuple (struct_time) has a total of nine elements. Because Python's time module implementation primarily calls the C library, each platform may be different.

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)    属性(Attribute)    值(Values)0     tm_year(年)                 比如2011 1     tm_mon(月)             1 - 122     tm_mday(日)                 1 - 313     tm_hour(时)                 0 - 234     tm_min(分)             0 - 595     tm_sec(秒)             0 - 616     tm_wday(weekday)            0 - 6(0表示周日)7     tm_yday(一年中的第几天)    1 - 3668     tm_isdst(是否是夏令时)            默认为-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: Time.strptime (' 2017-10-3 17:54 ', "%y-%m-%d%h:%m") #输出 time.struct_time (tm_year=2017, tm_mon=10, tm_mday=3, Tm_hour =17, tm_min=54, tm_sec=0, Tm_wday=1, tm_yday=276, 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).
%% A literal ‘%‘ character.

Finally, in order to easily remember the conversion relationship, see

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
d.timestamp(),d.today(), d.year,d.timetuple()等方法可以调用

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

3. Time arithmetic

>>> datetime.datetime.now()datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)>>> datetime.datetime.now() + datetime.timedelta(4) #当前时间 +4天datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)>>> datetime.datetime.now() + datetime.timedelta(hours=4) #当前时间+4小时datetime.datetime(2017, 10, 1, 16, 53, 42, 876275)

4. Time Replacement

>>> d.replace(year=2999,month=11,day=30)datetime.date(2999, 11, 30)


In [1time in[2time. localtime () out[2time. Struct_time (tm_year=2018, tm_mon=1, tm_mday=, tm_hour=,tm_min=40 , tm_sec=, tm_wday=3, tm_yday=,tm_isdst=0)
in [5]: a = Time. LocalTime () in [6]: aout[6]: Time. Struct_time (tm_year=2018, tm_mon=1, tm_mday= -, tm_hour= -, tm_min= A, tm_sec= -, tm_wday=3, tm_yday= -, tm_isdst=0) in [7]: A.a.count a.tm_hour a.tm_wdaya.index a.tm_isdst a.tm_ydaya.n_fields             A.tm_mday a.tm_yeara.n_sequence_fields a.tm_min a.tm_zonea.n_unnamed_fields A.tm_mon A.tm_gmtoff a.tm_sec in [7]: a.tm_yearout[7]:2018In [8]:'%s-%s-%s'%(a.tm_year,a.tm_mon,a.tm_) a.tm_gmtoff a.tm_mday a.tm_sec a.tm_yeara.tm_hour a.tm_min a.tm_wday a.tm _ZONEA.TM_ISDST A.tm_mon a.tm_yday in [8]:'%s-%s-%s'%(a.tm_year,a.tm_mon,a.tm_mday) out[8]:'2018-1-25'

 

Python Basics-4.1 Time module

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.