Reference Manual for the datetime module in Python

Source: Internet
Author: User
Tags timedelta
Python processes the time and date modules, mainly using the datetime, time, and calendar modules. The following article mainly introduces the datetime module in Python. you can refer to it for reference. let's take a look at it. Preface

Python provides multiple built-in modules for date and time operations, such as calendar, time, and datetime. The interfaces provided by the time module are basically the same as those provided by the C standard library time. h. Compared with the time module, the datetime module interface is more intuitive and easier to call.

The module defines two constants:

Datetime. MINYEAR

Datetime. MAXYEAR

The two constants represent the minimum and maximum year that datetime can represent. MINYEAR = 1, MAXYEAR = 9999.

The datetime module defines the following classes:

Datetime. date: indicates the date class. Common attributes include year, month, and day;

Datetime. time: indicates the time class. Common attributes include hour, minute, second, and microsecond;

Datetime. datetime: indicates the date and time.

Datetime. timedelta: indicates the time interval, that is, the length between two time points.

Datetime. tzinfo: time zone-related information.

Note: The objects listed above are immutable.

Date class

The date class represents a date (composed of years, months, and days). its prototype is as follows:

Class datetime. date (year, month, day)

Parameter description:

The range of year is [MINYEAR, MAXYEAR], that is, [1, 9999];

The range of month is [1, 12]. (The month starts from 1, not from 0 );

The maximum value of day is determined by the given year and month parameters. For example, there are 29 days in March of the leap year;

The date class defines some common class methods and class attributes:

Date. max, date. min: The maximum and minimum date that the date object can represent;

Date. resolution: the minimum unit of the date object. Here is the day.

Date. today (): returns a date object that represents the current local date;

Date. fromtimestamp (timestamp): returns a date object based on the given time period;

Datetime. fromordinal (ordinal): converts a Gregorian Calendar time to a date object. (Gregorian Calendar: a Calendar representation method. similar to China's lunar Calendar, many Western countries use it, we will not discuss it in detail here .)

Example:

>>> datetime.date.maxdatetime.date(9999, 12, 31)>>> datetime.date.mindatetime.date(1, 1, 1)>>> datetime.date.resolutiondatetime.timedelta(1)>>> datetime.date.today()datetime.date(2016, 5, 12)>>> datetime.date.fromtimestamp(time.time())datetime.date(2016, 5, 12)


Date provides the following instance methods and attributes:

Date. year, date. month, date. day: year, month, and day;

Date. replace (year, month, day): generates a new date object, replacing the attributes of the original object with the year, month, and day specified by the parameter. (The original object remains unchanged)

Date. timetuple (): returns the time. struct_time object corresponding to the date;

Date. toordinal (): returns the Gregorian Calendar date corresponding to the date;

Date. weekday (): return weekday. if it is Monday, return 0; if it is Day 2, return 1, and so on;

Data. isoweekday (): returns weekday. if it is Monday, 1 is returned. if it is Day 2, 2 is returned, and so on;

Date. isocalendar (): returns the tuples in the format of (year, month, day;

Date. isoformat (): returns a string in the format of 'yyyy-MM-DD;

Date. strftime (fmt): custom formatted string.

Example:

>>> today = datetime.date.today()>>> today.year2016>>> today.month5>>> today.day12>>> tomorrow = today.replace(day=13)>>> tomorrowdatetime.date(2016, 5, 13)>>> tomorrow.timetuple()time.struct_time(tm_year=2016, tm_mon=5, tm_mday=13, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=134, tm_isdst=-1)>>> tomorrow.toordinal()736097>>> tomorrow.weekday()4>>> tomorrow.isoweekday()5>>> tomorrow.isocalendar()(2016, 19, 5)>>> tomorrow.isoformat()'2016-05-13'>>> tomorrow.strftime("%y-%m-%d")'16-05-13'


Date reloads simple operators:

Date allows addition, subtraction, and comparison of dates:

Date2 = date1 + timedelta:

Returns a new date object with an interval

Date2 = date1-timedelta:

Returns a new date object.

Timedelta = date1-date2:

Returns a time interval object.

Date1 <date2:

Compare two dates.

Example:

>>> now = datetime.date.today()>>> nowdatetime.date(2016, 5, 12)>>> now += datetime.date.resolution>>> nowdatetime.date(2016, 5, 13)>>> now -= datetime.date.resolution>>> nowdatetime.date(2016, 5, 12)>>> now < datetime.date.maxTrue


Time class

The time class indicates the time (consisting of hour, minute, second, and microsecond). its prototype is as follows:

Class datetime. time (hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None)

Parameter description:

The hour range is [0, 24 ),

Minute ranges from 0 to 60 ),

The second range is [0, 60 ),

The microsecond range is [0, 1000000 ),

Tzinfo indicates the time zone information.

Class attributes defined by the time class:

Time. min and time. max: minimum and maximum time that can be expressed by the time class. Where, time. min = time (0, 0, 0, 0), time. max = time (23, 59, 59,999 999 );

Time. resolution: minimum unit of time, which is 1 microsecond;

Example:

>>> datetime.time.mindatetime.time(0, 0)>>> datetime.time.maxdatetime.time(23, 59, 59, 999999)>>> datetime.time.resolutiondatetime.timedelta(0, 0, 1)


Instance methods and attributes provided by the time class:

Time. hour, time. minute, time. second, time. microsecond: hour, minute, second, microsecond;

Time. tzinfo: time zone information;

Time. replace ([hour [, minute [, second [, microsecond [, tzinfo]): creates a new time object, replace the attribute in the original object with the time, minute, second, and microsecond specified by the parameter (the original object remains unchanged );

Time. isoformat (): returns a string representation in the format of "HH: MM: SS;

Time. strftime (fmt): returns a custom formatted string.

Example:

>>> tm = datetime.time(18, 18, 18)>>> tm.hour18>>> tm.minute18>>> tm.second18>>> tm.microsecond0>>> tm.tzinfo>>> tm.isoformat()'18:18:18'>>> tm.replace(hour=20)datetime.time(20, 18, 18)>>> tm.strftime("%I:%M:%S %p")'06:18:18 PM'


Objects of the time class can only be compared, and addition and subtraction cannot be performed.

Datetime type

Datetime is a combination of date and time, including all information about date and time. The prototype is as follows:

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)


The meanings of parameters are the same as those in the constructors of date and time. pay attention to the parameter value range.

The class attributes and methods defined by the datetime class:

Datetime. min and datetime. max: minimum and maximum values that can be expressed by datetime;

Datetime. resolution: minimum unit of datetime;

Datetime. today (): returns a datetime object that represents the current local time;

Datetime. now ([tz]): returns a datetime object that represents the current local time. if the parameter tz is provided, the local time indicated by the tz parameter is obtained;

Datetime. utcnow (): returns a datetime object of the current utc time;

Datetime. fromtimestamp (timestamp [, tz]): Creates a datetime object based on the time period. The parameter tz specifies the time zone information;

Datetime. utcfromtimestamp (timestamp): create a datetime object according to the time limit;

Datetime. combine (date, time): Creates a datetime object based on date and time;

Datetime. strptime (date_string, format): converts a format string to a datetime object. this method is not provided for the data and time classes.

Example:

>>> datetime.datetime.mindatetime.datetime(1, 1, 1, 0, 0)>>> datetime.datetime.maxdatetime.datetime(9999, 12, 31, 23, 59, 59, 999999)>>> datetime.datetime.resolutiondatetime.timedelta(0, 0, 1)>>> print datetime.datetime.resolution0:00:00.000001>>> today = datetime.datetime.today()>>> todaydatetime.datetime(2016, 5, 12, 12, 46, 47, 246240)>>> datetime.datetime.now()datetime.datetime(2016, 5, 12, 12, 47, 9, 850643)>>> datetime.datetime.utcnow()datetime.datetime(2016, 5, 12, 4, 47, 42, 188124)>>> datetime.datetime.fromtimestamp(time.time())datetime.datetime(2016, 5, 12, 12, 48, 40, 459676)>>> datetime.datetime.combine(datetime.date(1990, 10, 05), datetime.time(18, 18, 18))datetime.datetime(1990, 10, 5, 18, 18, 18)>>> datetime.datetime.strptime("2010-04-07 01:48:16.234000", "%Y-%m-%d %H:%M:%S .%f")datetime.datetime(2010, 4, 7, 1, 48, 16, 234000)


Datetime instance methods and attributes

The instance method and attribute functions provided by the datetime class are similar to those provided by date and time. only the method names are listed here:

Datetime. year, month, day, hour, minute, second, microsecond, tzinfo:

Datetime. date (): obtains the date object;

Datetime. time (): get the time object;

Datetime. replace ([year [, month [, day [, hour [, minute [, second [, microsecond [, tzinfo]):

** Datetime. timetuple ()**

** Datetime. utctimetuple ()**

Datetime. toordinal ()

Datetime. weekday ()

Datetime. isocalendar ()

Datetime. isoformat ([sep])

Datetime. ctime (): returns a C-format string of the date and time, equivalent to time. ctime (time. mktime (dt. timetuple ()));

Datetime. strftime (format)

Datetime objects can also be compared, or a time interval object is returned by subtraction, or a new date and time object is returned by adding an interval to the date and time.

Timedelta class

The datetime. timedelta object represents the time difference between two time points. when two date or datetime objects are subtracted, a timedelta object is returned. The prototype is as follows:

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)


All parameters are optional and the default value is 0. the parameter value can be an integer, floating point number, positive number, or negative number.

Only days, seconds, and microseconds are stored internally. values of other parameters are automatically converted according to the following rules:

1 millisecond (millisecond) to 1000 microseconds (microsecond)

1 minute to 60 seconds

1 hour is converted to 3600 seconds

1 week to 7 days

The values of the three parameters are as follows:

0 <= microseconds <1000000

0 <= seconds <3600*24 (the number of seconds in one day)

-999999999 <= days <= 999999999

Class attributes defined by the timedelta class:

Timedelta. min: The minimum value of the time interval object, that is, timedelta (-999999999 ).

Timedelta. max: maximum value of the time interval object, that is, timedelta (days = 999999999, hours = 23, minutes = 59, seconds = 59, microseconds = 999999 ).

Timedelta. resolution: the minimum unit of time interval, that is, timedelta (microseconds = 1 ).

Example:

>>> datetime.timedelta.mindatetime.timedelta(-999999999)>>> datetime.timedelta.maxdatetime.timedelta(999999999, 86399, 999999)>>> datetime.timedelta.resolutiondatetime.timedelta(0, 0, 1)>>> print datetime.timedelta.resolution0:00:00.000001


Timedelta instance method

Timedelta. total_seconds (): calculates the total number of seconds of the interval.

Example:

>>> datetime.timedelta.resolution.total_seconds()1e-06


Format string

The strftime () method is provided for datetime, date, and time. This method receives a format string and outputs a string representation of the date and time. The supported conversion formats are as follows:

% Astar short. For example, Wednesday is a full write of Web % ASTAR. For example, Wednesday % B is short for Wednesday. For example, if February is Apr % B. For example, February is the string representation of April % c: Date and time. (For example, 04/07/10 10:43:39) % d: number of days in the month (the day of the month) % f: microsecond (in the range of []) % H: hour (in 24-hour format, [0, 23]) % I: Hour (in 12-hour format, [0, 11]) % j: days in the year [001,366] (the day of the year) % m: Month ([]) % M: minute ([]) % p: AM or PM % S: Second (range: [], why not [00, 59], refer to the python manual ~ _~) % U: The week in the current year's week number in the current year's week), Sunday as the first day of the week % w: Today in this week's day, range: [0, 6], 6 indicates Sunday % W: The number of weeks in the current year (the week of the current year), and Monday as the first day of the week % x: date string (for example, 04/07/10) % X: time String (for example, 10: 43: 39) % y: 2 digits indicate the year % Y: 4 digits indicate the year % z: the interval between the time and utc (if the local time is used, an empty string is returned) % Z: time zone name (if the local time is used, an empty string is returned) %: % => %


Example:

>>> dt = datetime.datetime.now()>>> dt.strftime('%Y-%m-%d %H:%M:%S %f')'2016-05-12 14:19:22 333943'>>> dt.strftime('%y-%m-%d %I:%M:%S %p')'16-05-12 02:19:22 PM'>>> dt.strftime("%a")'Thu'>>> dt.strftime("%A")'Thursday'>>> dt.strftime("%b")'May'>>> dt.strftime("%B")'May'>>> dt.strftime("%c")'Thu May 12 14:19:22 2016'>>> dt.strftime("%x")'05/12/16'>>> dt.strftime("%X")'14:19:22'>>> dt.strftime("%w")'4'>>> dt.strftime("%j")'133'>>> dt.strftime("%u")'4'>>> dt.strftime("%U")'19'


Summary

The above is all about this article. I hope this article will help you in your study or work. if you have any questions, please leave a message.

For more articles about the datetime module reference manual in Python, refer to the Chinese PHP website!

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.