Reference manual for the datetime module in Python

Source: Internet
Author: User
Tags date1 difference between two times local time timedelta
Objective

Python provides several built-in modules for manipulating date times, like Calendar,time,datetime. The interface provided by the time module is basically consistent with the C standard library time.h. The interface of the DateTime module is more intuitive and easier to invoke than the time module.

The module defines two constants:

Datetime. Minyear

Datetime. Maxyear

These two constants represent the minimum and maximum year that datetime can represent. wherein, Minyear = 1,maxyear = 9999.

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.

Note: These types of objects listed above are immutable (immutable).

Date class

The date class represents a day, consisting of the year, month, and day, and is prototyped as follows:

Class Datetime.date (year, month, day)

Parameter description:

The range of year is [Minyear, maxyear], i.e. [1, 9999];

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

The maximum value of day is determined by the given year, month parameter. For example leap year February has 29 days;

The date class defines some commonly used class methods and class properties:

The maximum and minimum date the Date.max and Date.min:date objects can represent;

The Date.resolution:date object represents the smallest unit of the date. This 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 timestamp;

Datetime.fromordinal (ordinal): Converts the Gregorian calendar time to a Date object; (Gregorian calendar: A calendar representation, similar to our Chinese lunar calendar, the western countries use more, here is not discussed in detail.) )

Examples of Use:

>>> datetime.date.maxdatetime.date (9999, 1) >>> datetime.date.mindatetime.date (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)


The instance methods and properties provided by date:

Date.year, Date.month, Date.day: Year, month, day;

Date.replace (year, Month, day): Generates a new Date object, substituting the attributes in the original object with the years, months, and days 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 date corresponding to the Gregorian calendar date;

Date.weekday (): Returns weekday, if it is Monday, returns 0 if it is Week 2, returns 1, and so on;

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

Date.isocalendar (): Returns a tuple with a format such as (Year,month,day);

Date.isoformat (): Returns a string formatted as ' YYYY-MM-DD ';

Date.strftime (FMT): Custom formatted string.

Examples of Use:

>>> today = Datetime.date.today () >>> today.year2016>>> today.month5>>> Today.day12>>> tomorrow = Today.replace (day=13) >>> tomorrowdatetime.date (5, all) >>> 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 () (5) >>> Tomorrow.isoformat () ' 2016-05-13 ' >>> tomorrow.strftime ("%y-%m-%d") ' 16-05-13 '


The date overloads the simple operator:

Date allows you to add and subtract dates:

Date2 = date1 + Timedelta:

Date plus an interval that returns a new Date object

Date2 = Date1-timedelta:

Date interval to return a new Date object

Timedelta = Date1-date2:

Two date subtraction, returns a time interval object

Date1 < date2:

Two dates to compare.

Examples of Use:

>>> now = Datetime.date.today () >>> nowdatetime.date (5, a) >>> now + = Datetime.date.resolution>>> nowdatetime.date (5,) >>> now-= datetime.date.resolution> >> Nowdatetime.date (5, a) >>> now < Datetime.date.maxTrue


Time class

The time class represents times (consisting of hours, minutes, seconds, and microseconds) and is prototyped as follows:

Class Datetime.time (hour=0, minute=0, Second=0, Microsecond=0, Tzinfo=none)

Parameter description:

The range of Hour is [0, 24),

The range of minute is [0, 60),

The range of second is [0, 60),

The range of microsecond is [0, 1000000),

Tzinfo represents the time zone information.

class properties defined by the time class:

The minimum and maximum time that the Time.min, Time.max:time class can represent. wherein, Time.min = time (0, 0, 0, 0), Time.max = time (23, 59, 59, 999999);

Time.resolution: The smallest unit of time, here is 1 microseconds;

Examples of Use:

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


The time class provides instance methods and properties:

Time.hour, Time.minute, Time.second, Time.microsecond: Hours, minutes, seconds, microseconds;

Time.tzinfo: time zone information;

Time.replace ([hour[, minute[, second[, microsecond[, Tzinfo]]]]): Creates a new time object with the time, minutes, seconds, and microseconds specified by the parameter instead of the attributes in the original object (the original object remains unchanged);

Time.isoformat (): A string representation of the return type, such as "HH:MM:SS" format;

Time.strftime (FMT): Returns a custom formatted string.

Examples of Use:

>>> TM = Datetime.time (up to) >>> tm.hour18>>> tm.minute18>>> tm.second18> >> tm.microsecond0>>> tm.tzinfo>>> Tm.isoformat () ' 18:18:18 ' >>> tm.replace (hour=20 (datetime.time) >>> tm.strftime ("%i:%m:%s%p") ' 06:18:18 PM '


Objects of the time class can be compared only and cannot be added or reduced.

DateTime class

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 each parameter are the same as in the constructor of date and time, so be aware of the range of parameter values.

The class properties and methods defined by the DateTime class:

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

Datetime.resolution:datetime minimum Unit;

Datetime.today (): Returns a DateTime object representing the current local time;

DateTime.Now ([TZ]): Returns a DateTime object that represents the current local time, and if the parameter tz is provided, gets the local time of the time zone referred to by the TZ parameter;

Datetime.utcnow (): Returns a DateTime object for the current UTC time;

Datetime.fromtimestamp (timestamp[, TZ]): Creates a DateTime object according to the time timestamp, and the parameter TZ specifies the time zone information;

Datetime.utcfromtimestamp (timestamp): Creates a DateTime object based on the time timestamp;

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, which is not provided by data and the time class.

Examples of Use:

>>> datetime.datetime.mindatetime.datetime (1, 1, 1, 0, 0) >> > datetime.datetime.maxdatetime.datetime (9999, I, I, 999999) >>> Datetime.datetime.resolutiondatetime.timedelta (0, 0, 1) >>> print datetime.datetime.resolution0:0 0:00.000001>>> today = Datetime.datetime.today () >>> todaydatetime.datetime (2016, 5, 12, 12, 46, 47, 246240) >>> Datetime.datetime.now () datetime.datetime (5, 9, 850643) >>> Datetime.datetime.utcnow () Datetime.datetime (5, 4, 188124) >>> Datetime.datetime.fromtimestamp (Time.time ()) Datetime.datetime (5, A, A, 459676) >>> Datetime.datetime.combine (Datetime.date (1990), Datetime.time (1990, 10, 5, 18, 18, Datetime.datetime) ) >>> datetime.datetime.strptime ("2010-04-07 01:48:16.234000", "%y-%m-%d%h:%m:%s.%f") Datetime.datetime ( , 4, 7, 1, 234000) 


Instance methods and properties for datetime

The instance methods and properties provided by the DateTime class are most functionally similar to date and time, where only the method names are not listed:

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

Datetime.date (): Gets the Date object;

Datetime.time (): Gets 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 datetime equivalent to Time.ctime (Time.mktime (Dt.timetuple ()));

Datetime.strftime (format)

A DateTime object can also be compared, or the subtraction returns a time interval object, or a date time plus an interval to return a new DateTime object.

Timedelta class

The Datetime.timedelta object represents the time difference between two times, and a Timedelta object can be returned when subtracting two date or DateTime objects. 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 are 0 by default, and the values of the parameters can be integers, floating-point numbers, positive or negative numbers.

The internal only stores days,seconds,microseconds, and the values of the other parameters are automatically captured as follows:

1 millisecond (ms) converted to microseconds (microseconds)

1 minute converted into seconds

1 hour converted into 3600 seconds

1 week converted to 7 days

The range of values for the three parameters is:

0 <= microseconds < 1000000

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

-999999999 <= days <= 999999999

class properties defined by the Timedelta class:

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

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

Timedelta.resolution: The smallest unit of time interval, which is Timedelta (Microseconds=1).

Examples of Use:

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


Timedelta instance method

Timedelta.total_seconds (): Calculates the total number of seconds in a time interval

Examples of Use:

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


format string

datetime, date, and time all provide the strftime () method, which receives a format string that outputs a string representation of the DateTime. The supported conversion formats are as follows:

%a Week's shorthand. As Wednesday for Web%a week's full write. For example, Wednesday is abbreviated for WEDNESDAY%B month. such as April for the full write of Apr%b month. As in April, april%c: A string representation of the DateTime. (Example: 04/07/10 10:43:39)%d: Days in this month (the day of the week)%f: microseconds (range [0,999999])%H: Hours (24-hour, [0,])%I: Hours (12-hour, [0, one])%j: Days in the year [ 001,366] (the day of the year)%m: Month ([01,12])%m: minutes ([00,59])%p:am or pm%s: seconds (range = [00,61], why not [00, 59], refer to Python manual ~_~)%u: Weeks in the current year of the Week of the year, Sunday as the first day of the week%w: Today in this week, the number of days, the range is [0, 6],6 represents Sunday%w: Week in the Year of the week (is the first week of the year), Monday as the day of the week%x: date string (such as: 04/07/10)%x: A time string (such as: 10:43:39)%y:2 A number representing the year%y:4 the year%Z: Interval from UTC (If local time, returns an empty string)%Z: Time zone name (returns an empty string if local time) percent:%


Examples of Use:

>>> 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 14:19:22 ' >>> 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 '


Summarize

The above is the entire content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.

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.