Python Module Learning datetime introduction _python

Source: Internet
Author: User
Tags date1 datetime local time time interval timedelta
The interface of the DateTime module is more intuitive and easier to invoke than the time module. Today we'll talk about the datetime module.

The DateTime module defines two constants: DateTime. Minyear and Datetime.maxyear, respectively, representing the minimum and maximum years that a datetime can represent. of which, minyear = 1,maxyear = 9999. (For even players, this range is enough to use ~ ~)

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. Commonly used properties are hour, minute, second, microsecond;
Datetime.datetime: Represents a DateTime.
Datetime.timedelta: Represents the time interval, that is, the length between two points in time.
Datetime.tzinfo: Related information about the time zone. (This class is not fully discussed here, and interested children's shoes can refer to the Python manual)
Note: These types of objects above are immutable (immutable).

The following is a detailed description of how these classes are used.

Date Class
The date class represents a day. The date consists of the year, the month, the day (the earth people all know ~ ~). The constructor for the date class is as follows:

Class Datetime.date (year, Month, day): The meaning of the argument is not much explained, just a few points to note:

The scope of the year is [Minyear, maxyear], i.e. [1, 9999];
The range of month is [1, 12]. (Month is starting from 1, not from the beginning of the 0 ~_~);
The maximum value of the day is determined according to the given year, month parameters. For example leap year February has 29 days;
The date class defines some common class methods and class attributes to facilitate our operation:

The maximum and minimum dates that can be expressed by Date.max and Date.min:date objects;
The Date.resolution:date object represents the smallest unit of a date. This is the day.
date.today (): Returns a Date object that represents the current local date;
Date.fromtimestamp (timestamp): Returns a Date object according to a given time timestamp;
datetime.fromordinal (ordinal): Converts the Gregorian calendar time to a Date object; (Gregorian calendar: A method of calendars, similar to the Chinese lunar calendar, used in Western countries, The discussion is not detailed here. )

Use examples:
Copy Code code as follows:

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

# #----The results----
# date.max:9999-12-31
# date.min:0001-01-01
# Date.today (): 2010-04-06
# Date.fromtimestamp (): 2010-04-06

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 that replaces 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 Gregorian calendar date corresponding to the date;
Date.weekday (): Return to weekday, if it is Monday, return 0; If it is the Week 2, return 1, etc.;
Data.isoweekday (): Return to weekday, if it is Monday, return 1; If it is the Week 2, return 2, etc.;
Date.isocalendar (): Returns a tuple of a format such as (Year,month,day);
Date.isoformat (): Returns a string formatted as ' YYYY-MM-DD ';
Date.strftime (FMT): Custom format string. Explained in detail below.

Use examples:
Copy Code code as follows:

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

# #----The results----
# 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 overloads some operations, which allow us to do some of the following things:

date2 = date1 + Timedelta # date plus an interval that returns a new Date object (Timedelta will be introduced below to indicate the time interval)
date2 = date1-timedelta # date spacer interval, returning a new Date object
Timedelta = date1-date2 # Two date subtraction, returns a time interval object
Date1 < Date2 # Two dates for comparison
Note: When you operate on a date, you prevent the date from exceeding the range it can represent.

Use examples:
Copy Code code as follows:

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

# #----The results----
# now:2010-04-06 Tomorrow:2010-04-07
# Timedelta:1 Day, 0:00:00
# 2010-04-07
# True

Time Class
Time classes represent times, which consist of hours, minutes, seconds, and microseconds. (I'm not from Mars ~ ~) The constructor for the time class is as follows:

Class Datetime.time (hour[, minute[, second[, microsecond[, Tzinfo]]]: The meaning of each parameter is not explained, here's a note of the parameter Tzinfo, which represents the time zone information. Note the range of parameters: Hour range is [0], minute range is [0], second range is [0], microsecond range is [0, 1000000].

class properties defined by the time class:

The minimum and maximum time that the time.min, Time.max:time class can represent. Among them, Time.min = time (0, 0, 0, 0), and Time.max = time (23, 59, 59, 999999);
time.resolution: The smallest unit of time, here is 1 microseconds;
Instance methods and properties provided by the time class:

Time.hour, Time.minute, Time.second, Time.microsecond: Time, minutes, seconds, microseconds;
Time.tzinfo: time zone information;
Time.replace ([hour[, minute[, second[, microsecond[, Tzinfo]]]: Creates a new time object that replaces the attributes in the original object with the time, minutes, seconds, and microseconds specified by the parameter (the original object remains unchanged);
Time.isoformat (): Returns a string representation of the form, such as "HH:MM:SS";
Time.strftime (FMT): Returns a custom format string. described in detail below;

Use examples:
Copy Code code as follows:

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

# #----The results----
# tm:23:46:10
# hour:23, minute:46, Second:10, microsecond:0
# tm1:20:46:10
# Isoformat (): 23:46:10

As with date, two time objects can be compared or subtracted to return an interval object. There are no examples here.

DateTime class
DateTime is a combination of date and time, including all information about date and time. Its constructors are as follows: Datetime.datetime (year, month, day[, hour[, minute[, second[, microsecond[, Tzinfo]]], and the meaning of each parameter is the same as the date, In the constructor of time, be aware of the range of parameter values.

Class properties and methods defined by the DateTime class:

The minimum value and the maximum value that can be expressed by Datetime.min and Datetime.max:datetime;
datetime.resolution:datetime Smallest 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 a 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 based on the timestamp, parameter TZ Specifies the time zone information;
Datetime.utcfromtimestamp (timestamp): Creates a DateTime object based on the 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;

Use examples:
Copy Code code as follows:

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

#----Results----
# datetime.max:9999-12-31 23:59:59.999999
# datetime.min:0001-01-01 00:00:00
# datetime.resolution:0:00:00.000001
# Today (): 2010-04-07 09:48:16.234000
# now (): 2010-04-07 09:48:16.234000
# UtcNow (): 2010-04-07 01:48:16.234000 # China at +8 time, with local time difference 8
# Fromtimestamp (tmstmp): 2010-04-07 09:48:16.234000
# Utcfromtimestamp (tmstmp): 2010-04-07 01:48:16.234000

The instance methods and properties provided by the DateTime class (many properties or methods have already appeared in date and time, have similar meaning here, listing only these method names, the meaning of which will not be introduced individually, refer to the previous explanation of date and time classes.) ):

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 date-time C format string, equivalent to Time.ctime (Time.mktime (Dt.timetuple ()));
datetime.strftime (format)
Like date, you can compare two DateTime objects, or subtract a time interval object, or a date time plus an interval to return a new DateTime object. Here does not provide a detailed example, the spectators themselves to try ~ ~

format string
datetime, date, and time provide a strftime () method that receives a format string, and a string representation of the output datetime. The following table is drawn from the Python manual, and I have made a simple translation (a little bit of the Interpreter ~ ~).

Format character meaning

%a Week's shorthand. such as Wednesday for the web
%a week's full write. such as Wednesday for Wednesday
Shorthand for%b month. such as April for APR
%b the full month. such as April for April
%c: A string representation of the date time. (such as: 04/07/10 10:43:39)
%d: Days in this month (is the day of the week)
%f: microseconds (range [0,999999])
%H: Hours (24-hour system, [0, 23])
%I: Hours (12-hour system, [0, 11])
%j: Days in the year [001,366] (is the day of the first days)
%m: Month ([01,12])
%m: Min ([00,59])
%p:am or PM
%s: Seconds (range is [00,61], why not [00, 59], reference Python manual ~_~)
%u: Weeks in the year of the Week of the year, Sunday as the first day of the week
%w: Today in this week's days, the range is [0, 6],6 says Sunday
%w: Weeks in the current year (the Week of the year), Monday as the first day of the week
%x: Date strings (such as: 04/07/10)
%x: Time string (for example: 10:43:39)
%y:2 a number of years
%y:4 a number of years
%z: Interval from UTC (If local time, returns an empty string)
%Z: Time zone name (if local time, returns an empty string)
%%:%% =>%

Example:
Copy Code code as follows:

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 time%%c:%s '% dt.strftime ('%c ')
print ' date%%x:%s '% dt.strftime ('%x ')
print ' time%%x:%s '% dt.strftime ('%x ')
print ' Today is the first%s day of the week '% dt.strftime ('%w ')
print ' Today is this year's%s day '% dt.strftime ('%j ')
print ' This week is the first%s week '% dt.strftime ('%u ')

# #----The results----
# (%y-%m-%d%h:%m:%s%f): 2010-04-07-10:52:18 937000
# (%y-%m-%d%h:%m:%s%p): 10-04-07 10:52:18 AM
#%a:wed
#%a:wednesday
#%B:APR
#%b:april
# Date Time%C:04/07/10 10:52:18
# date%X:04/07/10
# time%x:10:52:18
# today is the 3rd day of the Week #
# today is the No. 097 Day of the year #
# This week is the 14th week of this year

These are the basic content of the DateTime module, finally finished ~~oh yeah~~

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.