Python Date Operation datetime

Source: Internet
Author: User
Tags date1 local time timedelta

The DateTime module defines the following classes:

Datetime.date: A class that represents a date. Common attributes are the year, month, Day.datetime.time: class that represents the time. Commonly used properties are hour, minute, second, Microsecond.datetime.datetime: Represents the date time. Datetime.timedelta: Represents the time interval, which is the length between two points in time. Datetime.tzinfo: Time zone-related information

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

Here is a detailed description of how these classes are used.

Date class

The date class represents a day. The date is made up of the year, month and day.

The constructor for the date class is as follows:

Class Datetime.date (year, Month, day):

Attention:

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

The range of month is [1, 12]

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 with the class properties L:

Date.max, Date.min:

The maximum, minimum date that can be represented by the date object.

The Date.resolution:date object represents the smallest unit of the date.

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.

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 that corresponds to the date.

Date.toordinal (): Returns the Gregorian calendar date corresponding to the 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.

Date also overloads some operations, which allow us to do some of the following with dates:

Date2 = date1 + Timedelta # date plus an interval, returns a new Date object (Timedelta will be described below, representing the time interval)

Date2 = date1-timedelta # date interval, returns a new Date object

Timedelta = date1-date2 # Two date subtraction, returns a time interval object

Date1 < Date2 # Two dates to compare

Note: When working on a date, prevent the date from exceeding the range it can represent.

Examples of Use:

>>> now = Date (at (), tomorrow) >>> = now.replace (day = +) >>> print ' Now: ', now, ', Tomor Row: ', tomorrownow:2012-02-24, tomorrow:2012-02-28>>> print ' Timetuple (): ', Now.timetuple () Timetuple (): ( 2, 0, 0, 0, 4, +,-1) >>> print ' Weekday (): ', Now.weekday () weekday (): 4>>> print ' Isoweekday () : ', Now.isoweekday () Isoweekday (): 5>>> print ' Isocalendar (): ', Now.isocalendar () Isocalendar (): (2012, 8, 5) >>> print ' Isoformat (): ', Now.isoformat () Isoformat (): 2012-02-24

Time class

The time class represents times, consisting of hours, minutes, seconds, and microseconds.

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, note here the parameter tzinfo, which represents the time zone information.

Take note of the range of values for each parameter:

The range of Hour is [0], the range of minute is [0], the range of second is [0], and the 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.

where 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.

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. Described in detail below.

>>> from datetime import *>>> TM = time (all, ten) >>> print ' TM: ', tmtm:22:19:10>>> print ' hour:%d, minute:%d, second:%d, microsecond:%d '         ... % (Tm.hour, Tm.minute, Tm.second, Tm.microsecond) hour:22, minute:19, second:10, microsecond:0>>> TM1 = Tm.rep Lace (hour =) >>> print ' TM1: ', tm1tm1:20:19:10>>> print ' Isoformat (): ', Tm.isoformat () Isoformat (): 22:19:10

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

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 meaning of each parameter is the same as the date, time As in the constructor, 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;

Examples of Use:

From datetime import *import time>>> print ' Datetime.max: ', datetime.maxdatetime.max:9999-12-31 23:59:59.999999>>> print ' datetime.min: ', datetime.mindatetime.min:0001-01-01 00:00:00>>> print ' Datetime.resolution: ', datetime.resolutiondatetime.resolution:0:00:00.000001>>> print ' Today (): ', Datetime.today () today (): 2012-02-24 22:17:36.945862>>> print ' Now (): ', DateTime.Now () Now (): 2012-02-24 22:17:36.966896>>> print ' UtcNow (): ', Datetime.utcnow () UtcNow (): 2012-02-24 14:17:36.976883

The instance methods and properties provided by the DateTime class:

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)

Like date, you can compare two DateTime objects, or subtract a time interval object, or return a new DateTime object with a DateTime plus an interval.

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 table below is drawn from the Python manual, and I have a simple translation.

Format character meaning

%a Week's shorthand. As Wednesday for web

%a week's full write. As in Wednesday for Wednesday

Abbreviated%B month. If April is Apr

Full write of%b month. As in April for April

%c: string representation of DateTime. (Example: 04/07/10 10:43:39)

%d: The number of days in the month (the day of the week)

%f: microseconds (range [0,999999])

%H: Hours (24-hour, [0, 23])

%I: Hours (12-hour, [0, 11])

%j: Number of days in the year [001,366] (the day of the current 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: Week 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 represents Sunday

%W: Week of the Year (the Week of the year), 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 the year represented by a number

%y:4 the year represented by a number

%z: Interval with UTC time (if local time, returns an empty string)

%Z: Time zone name (if local time, returns an empty string)

Percent:%

Example:

>>> dt = DateTime.Now () >>> print ' (%y-%m-%d%h:%m:%s%f): ', Dt.strftime ( '%y-%m-%d%h:%m:%s%f ') (%y-%m-%d%h:%m:%s%f): 2012-02-24 22:16:34%f>>> print ' (%y-%m-%d%h:%m:%s%p): ', Dt.st Rftime ('%y-%m-%d%i:%m:%s%p ') (%y-%m-%d%h:%m:%s%p): 12-02-24 10:16:34 pm>>> print '%%a:%s '% dt.strftime ('%a  ')%a:fri >>> print '%%a:%s '% dt.strftime ('%a ')%a:friday >>> print '%%b:%s '% dt.strftime ('%b ')%b: Feb >>> print '%%b:%s '% dt.strftime ('%B ')%b:february >>> print ' Date time%%c:%s '% dt.strftime ('%c ') date Time%c:fri Feb 22:16:34 >>> print ' date%%x:%s '% dt.strftime ('%x ') date%x:02/24/12 >>> print ' Time%%x:% S '% dt.strftime ('%x ') time%x:22:16:34 >>> print ' Today is this week's%s days '% dt.strftime ('%w ') today is the 5th day of this week >>> print ' Today is This year's%s days '% dt.strftime ('%j ') today is the No. 055 Day of this year >>> print ' This week is this year's%s week '% dt.strftime ('%u ') this week is the No. 08 week >>> 

#coding =utf-8import timeimport datetime# Gets the current time print time.localtime () print datetime.datetime.now () #计算两个日期之间的天数d1 = Datetime.datetime (2012,4,9) d2=datetime.datetime (2012,4,10) print (D2-D1). days# The run time of the calculation program is displayed in seconds starttime= Datetime.datetime.now () # do something Hereendtime=datetime.datetime.now () print (endtime-starttime). seconds# Calculates the date of N days D1=datetime.datetime.now () D2=d1=datetime.timedelta (days=10) print str (d2) # The previous example demonstrates the time to calculate the current time backwards by 10 days. # if it's the hour days change to hours#, the classes used in this book are: DateTime and Timedelta two. They can be added and reduced between each other. # Each class has some methods and properties to view specific values, such as DateTime can be viewed: Days, # #小时数 (Hour), weekday (weekday ()), etc. # Timedelta can view: days, seconds (seconds), etc. #string-Timea=time.strptime (' 2012-03-05 16:26:23 ', "%y-%m-%d%h:%m:%s") Print A#time = String#time.strftime (" %y-%m-%d%h:%m:%s ",)

Python Date Operation datetime

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.