Description of the datetime module in the python time module

Source: Internet
Author: User
Tags timedelta
This article mainly introduces the datetime module in the python time module. The interface of the datetime module is more intuitive and easier to call, if you want to know about the datetime module, you can refer to Python to provide multiple built-in modules for date and time operations, such as calendar, time, and datetime. I have already introduced the time module in my previous articles. 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.
1. datetime contains three types: date, time, datetime
The datetime. combine (date, time) function can obtain dateime, datetime. date (), datetime. time (), and date and time.

2. Convert datetime time to string

Let's talk about the datetime module today.

1. The datetime module defines two constants:Datetime. MINYEAR and datetime. MAXYEAR indicate the minimum and maximum years that datetime can represent. MINYEAR = 1, MAXYEAR = 9999.

2. 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 above types of objects are immutable.

The following describes how to use these classes.

I. date class

The date class represents a date. The date is composed of years, months, and days (everyone on Earth knows ~~). The constructor of the date class is as follows:

Class datetime. date (year, month, day): the meaning of the parameter is not explained much, but pay attention to the following points:

  • 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 for our convenience:

  • 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:

From datetime import * import time print 'date. max: ', date. max print 'date. min: ', date. min print 'date. today (): ', date. today () print 'date. fromtimestamp (): ', date. fromtimestamp (time. time () # ---- result ---- # date. maximum: 9999-12-31 # date. minute: 0001-01-01 # date. today (): 2010-04-06 # date. fromtimestamp (): 2010-04-06

From datetime import * import time print 'date. max: ', date. max print 'date. min: ', date. min print 'date. today (): ', date. today () print 'date. fromtimestamp (): ', date. fromtimestamp (time. time () # ---- result ----
# Date. max: 9999-12-31
# Date. min: 0001-01-01
# Date. today (): 2010-04-06
# Date. fromtimestamp (): 2010-04-06

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. The following is a detailed description.

Example:

Now = date (2010, 04, 06) tomorrow = now. replace (day = 07) print 'now: ', now,', tomorrow: ', tomorrow print 'timetuple ():', now. timetuple () print 'weekday (): ', now. weekday () print 'isoweekday (): ', now. isoweekday () print 'isocalendar (): ', now. isocalendar () print 'isoformat (): ', now. isoformat () ##---- result ---- # now: 2010-04-06, tomorrow: 2010-04-07 # timetuple (): (2010, 4, 6, 0, 0, 0, 1, 96, -1) # weekday (): 1 # isoweekday (): 2 # isocalendar (): (2010, 14, 2) # isoformat (): 2010-04-06

Now = date (2010, 04, 06) tomorrow = now. replace (day = 07) print 'now: ', now,', tomorrow: ', tomorrow print 'timetuple ():', now. timetuple () print 'weekday (): ', now. weekday () print 'isoweekday (): ', now. isoweekday () print 'isocalendar (): ', now. isocalendar () print 'isoformat (): ', now. isoformat () ##---- result ---- # now: 2010-04-06, tomorrow: 2010-04-07 # timetuple (): (2010, 4, 6, 0, 0, 0, 1, 96, -1) # weekday (): 1 # isoweekday (): 2 # isocalendar (): (2010, 14, 2) # isoformat (): 2010-04-06

Date also reloads some operations, which allow us to perform the following operations on the date:

  • Date2 = date1 + timedelta # date plus an interval, a new date object is returned (timedelta will be described below, indicating the interval)
  • Date2 = date1-timedelta # Return a new date object after the date separation interval.
  • Timedelta = date1-date2 # subtract two dates and return a time interval object
  • Date1 <date2 # compare two dates

Note: When you operate a date, you must prevent the date from exceeding the range it can represent.
Example:

Now = date. today () tomorrow = now. replace (day = 7) delta = tomorrow-now print 'now: ', now, 'Tomorrow:', tomorrow print 'timedelta :', delta print now + delta print tomorrow> now ##---- result ---- # now: 2010-04-06 tomorrow: 2010-04-07 # timedelta: 1 day, 0:00:00 #2010-04-07 # True

Now = date. today () tomorrow = now. replace (day = 7) delta = tomorrow-now print 'now: ', now, 'Tomorrow:', tomorrow print 'timedelta :', delta print now + delta print tomorrow> now ##---- result ---- # now: 2010-04-06 tomorrow: 2010-04-07 # timedelta: 1 day, 0:00:00 #2010-04-07 # True

Ii. Time

The time class indicates the time, which consists of hour, minute, second, And microsecond. The constructor of the time class is as follows:

Class datetime. time (hour [, minute [, second [, microsecond [, tzinfo]): the meaning of each parameter is not explained. Pay attention to the parameter tzinfo, which indicates the time zone information. Note that the value range of each parameter is [0, 24), [0, 60), and [0, 60 ), the microsecond range is [0, 1000000 ).

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;

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. The details are as follows;

Example:

From datetime import * tm = time (23, 46, 10) print 'Tm: ', tm print 'hour: % d, minute: % d, second: % d, microsecond: % d' \ % (tm. hour, tm. minute, tm. second, tm. microsecond) tm1 = tm. replace (hour = 20) print 'tm1: ', tm1 print 'isoformat ():', tm. isoformat () ##---- result ---- # tm: 23:46:10 # hour: 23, minute: 46, second: 10, microsecond: 0 # tm1: 20:46:10 # isoformat (): 23:46:10

From datetime import * tm = time (23, 46, 10) print 'Tm: ', tm print 'hour: % d, minute: % d, second: % d, microsecond: % d' \ % (tm. hour, tm. minute, tm. second, tm. microsecond) tm1 = tm. replace (hour = 20) print 'tm1: ', tm1 print 'isoformat ():', tm. isoformat () ##---- result ---- # tm: 23:46:10 # hour: 23, minute: 46, second: 10, microsecond: 0 # tm1: 20:46:10 # isoformat (): 23:46:10

Like date, you can compare two time objects or subtract to return a time interval object. Examples are not provided here.

Iii. datetime class

Datetime is a combination of date and time, including all information about date and time. Its constructor is as follows: datetime. datetime (year, month, day [, hour [, minute [, second [, microsecond [, tzinfo]), 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;

Example:

From datetime import * import time print 'datetime. max: ', datetime. max print 'datetime. min: ', datetime. min print 'datetime. resolution: ', datetime. resolution print 'today (): ', datetime. today () print 'now (): ', datetime. now () print 'utcnow (): ', datetime. utcnow () print 'fromtimestamp (tmstmp): ', datetime. fromtimestamp (time. time () print 'utcfromtimestamp (tmstmp): ', datetime. utcfromtimestamp (time. time () # ---- result ---- # datetime. max: 9999-12-31 23:59:59. 999999 # datetime. min: 0001-01-01 00:00:00 # datetime. resolution: 0:00:00. 000001 # today (): 09:48:16. 234000 # now (): 09:48:16. 234000 # utcnow (): 01:48:16. 234000 # China is located at + 8 time, which is different from the local time by 8 # fromtimestamp (tmstmp): 09:48:16. 234000 # utcfromtimestamp (tmstmp): 01:48:16. 234000

From datetime import * import time print 'datetime. max: ', datetime. max print 'datetime. min: ', datetime. min print 'datetime. resolution: ', datetime. resolution print 'today (): ', datetime. today () print 'now (): ', datetime. now () print 'utcnow (): ', datetime. utcnow () print 'fromtimestamp (tmstmp): ', datetime. fromtimestamp (time. time () print 'utcfromtimestamp (tmstmp): ', datetime. utcfromtimestamp (time. time () # ---- result ---- # datetime. max: 9999-12-31 23:59:59. 999999 # datetime. min: 0001-01-01 00:00:00 # datetime. resolution: 0:00:00. 000001 # today (): 09:48:16. 234000 # now (): 09:48:16. 234000 # utcnow (): 01:48:16. 234000 # China is located at + 8 time, which is different from the local time by 8 # fromtimestamp (tmstmp): 09:48:16. 234000 # utcfromtimestamp (tmstmp): 01:48:16. 234000

The instance methods and Attributes provided by the datetime class (many attributes or methods have already appeared in date and time, which have similar meanings here. Here, only the names of these methods are listed, the specific meanings will not be described one by one. You can refer to the previous sections on the date and time classes .) :

  • 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)

Like date, you can also compare two datetime objects, or subtract to return a time interval object, or add an interval to return a new date and time object. No detailed examples are provided here. You can try it yourself ~~

4. convert to a 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 following table is pulled from the python manual. I have made some simple translations ~~).

Format characters and meanings

%. For example, Wednesday is Web
% A full write of the week. Wednesday for Example
The abbreviation of month % B. For example, in March, Apr
% B. For example, in February
% C: String Representation of the date and time. (For example, 04/07/10 10:43:39)
% D: The day of the month (the day of the month)
% F: microsecond (range: [0, 999999])
% H: hour (in 24-hour format, [0, 23])
% I: hour (in 12-hour format, [0, 11])
% J: number of days in the year [001,366] (the day of the year)
% M: Month ([0, 12])
% M: minute ([])
% P: AM or PM
% S: Second (range: []. Why not [00, 59]? refer to the python manual ~ _~)
% U: the number of weeks in the current year.) Sunday is the first day of the week.
% W: the number of days of the current week. The value range is [0, 6]. 6 indicates Sunday.
% W: the number of weeks in the current year (the week of the current year). Monday is the first day of the week.
% X: Date string (for example: 04/07/10)
% X: Time string (for example, 10: 43: 39)
% Y: The year indicated by two digits
% Y: The year represented by four digits
% Z: the time interval from utc (if it is a local time, an empty string is returned)
% Z: Time Zone name (if it is a local time, an empty string is returned)
%: % => %

Example:

Dt = datetime. now () print '(% Y-% m-% d % H: % M: % S % f):', dt. strftime ('% Y-% m-% d % H: % M: % S % F') print' (% Y-% m-% d % H: % M: % S % p): ', dt. strftime ('% y-% m-% d % I: % M: % S % p') print' % a: % s' % dt. strftime ('% A') print' % a: % s' % dt. strftime ('% A') print' % B: % s' % dt. strftime ('% B') print '% B: % s' % dt. strftime ('% B') print 'date and time % c: % s' % dt. strftime ('% C') print' date % x: % s' % dt. strftime ('% x') print' time % x: % s' % dt. strftime ('% x') print' today is the % s day of the week '% dt. strftime ('% W') print' today is the % s day of this year '% dt. strftime ('% J') print' this week is the % s week of this year '% dt. strftime ('% U') ##---- result ---- # (% Y-% m-% d % H: % M: % S % f ): 10:52:18 937000 # (% Y-% m-% d % H: % M: % S % p): 10-04-07 10:52:18 AM # %: wed # % A: Wednesday # % B: Apr # % B: April # date and time % c: 04/07/10 10:52:18 # date % x: 04/07/10 # Time % X: 10: 52: 18 # today is the 3rd day of this week # today is the 097th day of this year # this week is the 14th week of this year

Dt = datetime. now () print '(% Y-% m-% d % H: % M: % S % f):', dt. strftime ('% Y-% m-% d % H: % M: % S % F') print' (% Y-% m-% d % H: % M: % S % p): ', dt. strftime ('% y-% m-% d % I: % M: % S % p') print' % a: % s' % dt. strftime ('% A') print' % a: % s' % dt. strftime ('% A') print' % B: % s' % dt. strftime ('% B') print '% B: % s' % dt. strftime ('% B') print 'date and time % c: % s' % dt. strftime ('% C') print' date % x: % s' % dt. strftime ('% x') print' time % x: % s' % dt. strftime ('% x') print' today is the % s day of the week '% dt. strftime ('% W') print' today is the % s day of this year '% dt. strftime ('% J') print' this week is the % s week of this year '% dt. strftime ('% U') ##---- result ---- # (% Y-% m-% d % H: % M: % S % f ): 10:52:18 937000 # (% Y-% m-% d % H: % M: % S % p): 10-04-07 10:52:18 AM # %: wed # % A: Wednesday # % B: Apr # % B: April # date and time % c: 04/07/10 10:52:18 # date % x: 04/07/10 # Time % X: 10: 52: 18 # today is the 3rd day of this week # today is the 097th day of this year # this week is the 14th week of this year

Time, datetime, and string Conversion in python

# Convert datetime to the string def datetime_toString (dt): return dt. strftime ("% Y-% m-% d-% H") # convert the string to datetime def string_toDatetime (string): return datetime. strptime (string, "% Y-% m-% d-% H") # convert the string to the timestamp format def string_toTimestamp (strTime): return time. mktime (string_toDatetime (strTime ). timetuple () # convert the timestamp to the string format def timestamp_toString (stamp): return time. strftime ("% Y-% m-% d-% H", tiem. localtime (stamp) # convert the datetime type to the external timestamp format def datetime_toTimestamp (dateTim): return time. mktime (dateTim. timetuple ())

The above is a detailed introduction of the datetime module in the python time module. I hope it will be helpful for your learning.

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.