How do you use days in python?
Source code: Lib/datetime.py Show
The While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. See also Modulecalendar General calendar related functions. Moduletime Time access and conversions. Modulezoneinfo Concrete time zones representing the IANA time zone database. Package dateutilThird-party library with expanded time zone and parsing support. Aware and Naive Objects¶Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information. With sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, an aware object can locate itself relative to other aware objects. An aware object represents a specific moment in time that is not open to interpretation. 1 A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality. For applications requiring aware objects,
Only one concrete
Constants¶The datetime. MINYEAR ¶The smallest year number allowed in a datetime. MAXYEAR ¶The largest year number allowed in a
Available Types¶classdatetime. date An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: datetime. time An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. (There is no notion of “leap seconds” here.)
Attributes: datetime. datetime A combination of a date and a time. Attributes: datetime. timedelta A duration expressing the difference between two datetime. tzinfo An abstract base class for time zone information objects. These are used by the
datetime. timezone A class that implements the New in version 3.2. Objects of these types are immutable. Subclass relationships: object timedelta tzinfo timezone time date datetime Common Properties¶The
Determining if an Object is Aware or Naive¶Objects of the
An object of type A
Otherwise, d is naive. A
Otherwise, t is naive. The distinction between aware and naive doesn’t apply to timedelta Objects¶A datetime. timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0,
weeks=0)¶All arguments are optional and default to Only days, seconds and microseconds are stored internally. Arguments are converted to those units:
and days, seconds and microseconds are then normalized so that the representation is unique, with
The following example illustrates how any arguments besides days, seconds and microseconds are “merged” and normalized into those three resulting attributes: >>> from datetime import timedelta >>> delta = timedelta( ... days=50, ... seconds=27, ... microseconds=10, ... milliseconds=29000, ... minutes=5, ... hours=8, ... weeks=2 ... ) >>> # Only days, seconds, and microseconds remain >>> delta datetime.timedelta(days=64, seconds=29156, microseconds=10) If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond using round-half-to-even tiebreaker. If no argument is a float, the conversion and normalization processes are exact (no information is lost). If the normalized value of
days lies outside the indicated range, Note that normalization of negative values may be surprising at first. For example: >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) >>> (d.days, d.seconds, d.microseconds) (-1, 86399, 999999) Class attributes: timedelta. min ¶The most negative timedelta. max ¶The most positive timedelta. resolution ¶The smallest possible difference between non-equal Note that, because of normalization, Instance attributes (read-only):
Supported operations:
Notes:
In addition to the operations listed above, Changed in version 3.2: Floor division and true division of a Comparisons of The comparisons >>> from datetime import timedelta >>> delta1 = timedelta(seconds=57) >>> delta2 = timedelta(hours=25, seconds=2) >>> delta2 != delta1 True >>> delta2 == 5 False For all other comparisons (such as >>> delta2 > delta1 True >>> delta2 > 5 Traceback (most recent call last): File " In Boolean contexts, a Instance methods: timedelta. total_seconds ()¶Return the total number of seconds contained in the duration. Equivalent to Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy. New in version 3.2. Examples of usage: timedelta¶An additional example of normalization: >>> # Components of another_year add up to exactly 365 days >>> from datetime import timedelta >>> year = timedelta(days=365) >>> another_year = timedelta(weeks=40, days=84, hours=23, ... minutes=50, seconds=600) >>> year == another_year True >>> year.total_seconds() 31536000.0 Examples of >>> from datetime import timedelta >>> year = timedelta(days=365) >>> ten_years = 10 * year >>> ten_years datetime.timedelta(days=3650) >>> ten_years.days // 365 10 >>> nine_years = ten_years - year >>> nine_years datetime.timedelta(days=3285) >>> three_years = nine_years // 3 >>> three_years, three_years.days // 365 (datetime.timedelta(days=1095), 3) date Objects¶A January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on. 2 classdatetime. date (year, month, day)¶All arguments are required. Arguments must be integers, in the following ranges:
If an argument outside those ranges is given, Other constructors, all class methods: classmethoddate. today ()¶Return the current local date. This is equivalent to date. fromtimestamp (timestamp)¶Return the local date corresponding to the POSIX timestamp, such as is returned by This may raise Changed in version 3.3: Raise date. fromordinal (ordinal)¶Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
date. fromisoformat (date_string)¶Return a >>> from datetime import date >>> date.fromisoformat('2019-12-04') datetime.date(2019, 12, 4) This is the inverse of New in version 3.7. classmethoddate. fromisocalendar (year,
week, day)¶Return a New in version 3.8. Class attributes: date. min ¶The earliest representable date, date. max ¶The latest representable date, date. resolution ¶The smallest possible difference between non-equal
date objects, Instance attributes (read-only): date. year ¶Between date. month ¶Between 1 and 12 inclusive. date. day ¶Between 1 and the number of days in the given month of the given year. Supported operations:
Notes:
In Boolean contexts, all Instance methods: date. replace (year=self.year,
month=self.month, day=self.day)¶Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. Example: >>> from datetime import date >>> d = date(2002, 12, 31) >>> d.replace(day=26) datetime.date(2002, 12, 26) date. timetuple ()¶Return a The hours, minutes and seconds are 0, and the DST flag is -1.
time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)) where date. toordinal ()¶Return the proleptic Gregorian ordinal of the date, where
January 1 of year 1 has ordinal 1. For any date. weekday ()¶Return the day of the week as an integer, where Monday is 0
and Sunday is 6. For example, date. isoweekday ()¶Return the day of the week as an integer,
where Monday is 1 and Sunday is 7. For example, date. isocalendar ()¶Return a named tuple object with three components: The ISO calendar is a widely used variant of the Gregorian calendar. 3 The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year. For example, 2004 begins on a Thursday, so the first week of ISO year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004: >>> from datetime import date >>> date(2003, 12, 29).isocalendar() datetime.IsoCalendarDate(year=2004, week=1, weekday=1) >>> date(2004, 1, 4).isocalendar() datetime.IsoCalendarDate(year=2004, week=1, weekday=7) Changed in version 3.9: Result changed from a tuple to a named tuple. date. isoformat ()¶
Return a string representing the date in ISO 8601 format, >>> from datetime import date >>> date(2002, 12, 4).isoformat() '2002-12-04' This is the inverse of date. __str__ ()¶For a date d, date. ctime ()¶Return a string representing the date: >>> from datetime import date >>> date(2002, 12, 4).ctime() 'Wed Dec 4 00:00:00 2002'
time.ctime(time.mktime(d.timetuple())) on platforms where the native C date. strftime (format)¶Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see strftime() and strptime() Behavior. date. __format__ (format)¶Same as Examples of Usage: date¶Example of counting days to an event: >>> import time >>> from datetime import date >>> today = date.today() >>> today datetime.date(2007, 12, 5) >>> today == date.fromtimestamp(time.time()) True >>> my_birthday = date(today.year, 6, 24) >>> if my_birthday < today: ... my_birthday = my_birthday.replace(year=today.year + 1) >>> my_birthday datetime.date(2008, 6, 24) >>> time_to_birthday = abs(my_birthday - today) >>> time_to_birthday.days 202 More examples of working with >>> from datetime import date >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 >>> d datetime.date(2002, 3, 11) >>> # Methods related to formatting string output >>> d.isoformat() '2002-03-11' >>> d.strftime("%d/%m/%y") '11/03/02' >>> d.strftime("%A %d. %B %Y") 'Monday 11. March 2002' >>> d.ctime() 'Mon Mar 11 00:00:00 2002' >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month") 'The day is 11, the month is March.' >>> # Methods for to extracting 'components' under different calendars >>> t = d.timetuple() >>> for i in t: ... print(i) 2002 # year 3 # month 11 # day 0 0 0 0 # weekday (0 = Monday) 70 # 70th day in the year -1 >>> ic = d.isocalendar() >>> for i in ic: ... print(i) 2002 # ISO year 11 # ISO week number 1 # ISO day number ( 1 = Monday ) >>> # A date object is immutable; all operations produce a new object >>> d.replace(year=2005) datetime.date(2005, 3, 11) datetime Objects¶A Like a Constructor: classdatetime. datetime (year, month, day,
hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *,
fold=0)¶The year, month and day arguments are required. tzinfo may be
If an argument outside those ranges is given, New in version 3.6: Added the Other constructors, all class methods: classmethoddatetime. today ()¶Return the current local datetime, with
Equivalent to: datetime.fromtimestamp(time.time()) See also This method is functionally equivalent to datetime. now (tz=None)¶Return the current local date and time. If optional argument tz is If tz is not This function is preferred over datetime. utcnow ()¶Return the current UTC date and time, with
This is like Warning Because naive datetime. fromtimestamp (timestamp, tz=None)¶Return the local date and time corresponding to the POSIX timestamp, such as is returned by If tz is not
Changed in version 3.3: Raise Changed in version 3.6:
datetime. utcfromtimestamp (timestamp)¶Return the UTC This may raise To get an aware datetime.fromtimestamp(timestamp, timezone.utc) On the POSIX compliant platforms, it is equivalent to the following expression: datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp) except the latter formula always supports the full years range: between Warning Because naive Changed in version 3.3: Raise
datetime. fromordinal (ordinal)¶Return the
datetime. combine (date, time,
tzinfo=self.tzinfo)¶Return a new For any
Changed in version 3.6: Added the tzinfo argument. classmethoddatetime. fromisoformat (date_string)¶Return a
Specifically, this function supports strings in the format: YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]] where Caution This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of
Examples: >>> from datetime import datetime >>> datetime.fromisoformat('2011-11-04') datetime.datetime(2011, 11, 4, 0, 0) >>> datetime.fromisoformat('2011-11-04T00:05:23') datetime.datetime(2011, 11, 4, 0, 5, 23) >>> datetime.fromisoformat('2011-11-04 00:05:23.283') datetime.datetime(2011, 11, 4, 0, 5, 23, 283000) >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00') datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc) >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) New in version 3.7. classmethoddatetime. fromisocalendar (year, week, day)¶Return a New in version 3.8. classmethoddatetime. strptime (date_string,
format)¶Return a This is equivalent to: datetime(*(time.strptime(date_string, format)[0:6]))
Class attributes: datetime. min ¶The earliest representable
datetime. max ¶The latest representable
datetime. resolution ¶The smallest possible difference between non-equal
Instance attributes (read-only): datetime. year ¶Between
datetime. month ¶Between 1 and 12 inclusive. datetime. day ¶Between 1 and the number of days in the given month of the given year. datetime. hour ¶In datetime. minute ¶In datetime. second ¶In datetime. microsecond ¶In datetime. tzinfo ¶The object passed as the tzinfo argument to the datetime. fold ¶In New in version 3.6. Supported operations:
Instance methods: datetime. date ()¶Return datetime. time ()¶Return Changed in version 3.6: The fold value is copied to the returned
datetime. timetz ()¶Return
Changed in version 3.6: The fold value is copied to the returned
datetime. replace (year=self.year, month=self.month, day=self.day, hour=self.hour,
minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)¶Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that New in version 3.6: Added the datetime. astimezone (tz=None)¶Return a If provided, tz must be an instance of a If called without arguments (or with If If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time data, use Note that the default
def astimezone(self, tz): if self.tzinfo is tz: return self # Convert self to UTC, and attach the new time zone object. utc = (self - self.utcoffset()).replace(tzinfo=tz) # Convert from UTC to tz's local time. return tz.fromutc(utc) Changed in version 3.3: tz now can be omitted. Changed in version 3.6: The datetime. utcoffset ()¶If Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes. datetime. dst ()¶If Changed in version 3.7: The DST offset is not restricted to a whole number of minutes. datetime. tzname ()¶If datetime. timetuple ()¶Return a
time.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst)) where datetime. utctimetuple ()¶If If d is aware, d is normalized to UTC time, by subtracting Warning Because naive datetime. toordinal ()¶Return the proleptic Gregorian ordinal of the date. The same as datetime. timestamp ()¶Return POSIX timestamp corresponding to the Naive For aware
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() New in version 3.3. Changed in version 3.6: The Note There is no method to obtain the POSIX timestamp directly from a naive timestamp = dt.replace(tzinfo=timezone.utc).timestamp() or by calculating the timestamp directly: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) datetime. weekday ()¶Return the day of the week as an integer,
where Monday is 0 and Sunday is 6. The same as datetime. isoweekday ()¶Return the day of the
week as an integer, where Monday is 1 and Sunday is 7. The same as datetime. isocalendar ()¶Return a named tuple with three components: datetime. isoformat (sep='T', timespec='auto')¶Return a string representing the date and time in ISO 8601 format:
If
Examples: >>> from datetime import datetime, timezone >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat() '2019-05-18T15:17:08.132263' >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat() '2019-05-18T15:17:00+00:00' The optional argument sep (default >>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): ... """A time zone with an arbitrary, constant -06:39 offset.""" ... def utcoffset(self, dt): ... return timedelta(hours=-6, minutes=-39) ... >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') '2002-12-25 00:00:00-06:39' >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat() '2009-11-27T00:00:00.000100-06:39' The optional argument timespec specifies the number of additional components of the time to include
(the default is
Note Excluded time components are truncated, not rounded.
>>> from datetime import datetime >>> datetime.now().isoformat(timespec='minutes') '2002-12-25T00:00' >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0) >>> dt.isoformat(timespec='microseconds') '2015-01-01T12:30:59.000000' New in version 3.6: Added the timespec argument. datetime. __str__ ()¶For a datetime. ctime ()¶Return a string representing the date and time: >>> from datetime import datetime >>> datetime(2002, 12, 4, 20, 30, 40).ctime() 'Wed Dec 4 20:30:40 2002' The output string will not include time zone information, regardless of whether the input is aware or naive.
time.ctime(time.mktime(d.timetuple())) on platforms where the
native C datetime. strftime (format)¶Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior. datetime. __format__ (format)¶Same as Examples of Usage: datetime¶Examples of working with >>> from datetime import datetime, date, time, timezone >>> # Using datetime.combine() >>> d = date(2005, 7, 14) >>> t = time(12, 30) >>> datetime.combine(d, t) datetime.datetime(2005, 7, 14, 12, 30) >>> # Using datetime.now() >>> datetime.now() datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 >>> datetime.now(timezone.utc) datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc) >>> # Using datetime.strptime() >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") >>> dt datetime.datetime(2006, 11, 21, 16, 30) >>> # Using datetime.timetuple() to get tuple of all attributes >>> tt = dt.timetuple() >>> for it in tt: ... print(it) ... 2006 # year 11 # month 21 # day 16 # hour 30 # minute 0 # second 1 # weekday (0 = Monday) 325 # number of days since 1st January -1 # dst - method tzinfo.dst() returned None >>> # Date in ISO format >>> ic = dt.isocalendar() >>> for it in ic: ... print(it) ... 2006 # ISO year 47 # ISO week 2 # ISO weekday >>> # Formatting a datetime >>> dt.strftime("%A, %d. %B %Y %I:%M%p") 'Tuesday, 21. November 2006 04:30PM' >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time") 'The day is 21, the month is November, the time is 04:30PM.' The
example below defines a from datetime import timedelta, datetime, tzinfo, timezone class KabulTz(tzinfo): # Kabul used +4 until 1945, when they moved to +4:30 UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc) def utcoffset(self, dt): if dt.year < 1945: return timedelta(hours=4) elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30): # An ambiguous ("imaginary") half-hour range representing # a 'fold' in time due to the shift from +4 to +4:30. # If dt falls in the imaginary range, use fold to decide how # to resolve. See PEP495. return timedelta(hours=4, minutes=(30 if dt.fold else 0)) else: return timedelta(hours=4, minutes=30) def fromutc(self, dt): # Follow same validations as in datetime.tzinfo if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # A custom implementation is required for fromutc as # the input to this function is a datetime with utc values # but with a tzinfo set to self. # See datetime.astimezone or fromtimestamp. if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE: return dt + timedelta(hours=4, minutes=30) else: return dt + timedelta(hours=4) def dst(self, dt): # Kabul does not observe daylight saving time. return timedelta(0) def tzname(self, dt): if dt >= self.UTC_MOVE_DATE: return "+04:30" return "+04" Usage of >>> tz1 = KabulTz() >>> # Datetime before the change >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1) >>> print(dt1.utcoffset()) 4:00:00 >>> # Datetime after the change >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1) >>> print(dt2.utcoffset()) 4:30:00 >>> # Convert datetime to another time zone >>> dt3 = dt2.astimezone(timezone.utc) >>> dt3 datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc) >>> dt2 datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz()) >>> dt2 == dt3 True time Objects¶A datetime. time (hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, *, fold=0)¶All arguments are optional. tzinfo may be
If an argument outside those ranges is given, Class attributes: time. min ¶The earliest representable
time. max ¶The latest representable time. resolution ¶The smallest possible difference between non-equal Instance attributes (read-only): time. hour ¶In time. minute ¶In time. second ¶In time. microsecond ¶In time. tzinfo ¶The object passed as the tzinfo argument to the
time. fold ¶In New in version 3.6.
If both comparands are aware, and have the same Changed in version 3.3: Equality comparisons between aware and naive In Boolean contexts, a Changed in version 3.5: Before Python 3.5, a Other constructor: classmethodtime. fromisoformat (time_string)¶Return a HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]] Caution This does not support parsing arbitrary ISO 8601 strings. It is only intended as the inverse operation of
Examples: >>> from datetime import time >>> time.fromisoformat('04:23:01') datetime.time(4, 23, 1) >>> time.fromisoformat('04:23:01.000384') datetime.time(4, 23, 1, 384) >>> time.fromisoformat('04:23:01+04:00') datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) New in version 3.7. Instance methods: time. replace (hour=self.hour, minute=self.minute,
second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)¶Return a
New in version 3.6: Added the time. isoformat (timespec='auto')¶Return a string representing the time in ISO 8601 format, one of:
The optional argument timespec specifies the number of additional components of the time to include (the default is
Note Excluded time components are truncated, not rounded.
Example: >>> from datetime import time >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes') '12:34' >>> dt = time(hour=12, minute=34, second=56, microsecond=0) >>> dt.isoformat(timespec='microseconds') '12:34:56.000000' >>> dt.isoformat(timespec='auto') '12:34:56' New in version 3.6: Added the timespec argument. time. __str__ ()¶For a time t, time. strftime (format)¶Return a string representing the time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior. time. __format__ (format)¶Same as time. utcoffset ()¶If Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes. time. dst ()¶If Changed in version 3.7: The DST offset is not restricted to a whole number of minutes. time. tzname ()¶If Examples of Usage: time¶Examples of working with a >>> from datetime import time, tzinfo, timedelta >>> class TZ1(tzinfo): ... def utcoffset(self, dt): ... return timedelta(hours=1) ... def dst(self, dt): ... return timedelta(0) ... def tzname(self,dt): ... return "+01:00" ... def __repr__(self): ... return f"{self.__class__.__name__}()" ... >>> t = time(12, 10, 30, tzinfo=TZ1()) >>> t datetime.time(12, 10, 30, tzinfo=TZ1()) >>> t.isoformat() '12:10:30+01:00' >>> t.dst() datetime.timedelta(0) >>> t.tzname() '+01:00' >>> t.strftime("%H:%M:%S %Z") '12:10:30 +01:00' >>> 'The {} is {:%H:%M}.'.format("time", t) 'The time is 12:10.' tzinfo Objects¶classdatetime. tzinfo ¶This is an abstract base class, meaning that this class should not be instantiated directly. Define a subclass of An
instance of (a concrete subclass of) You need to derive a concrete subclass, and (at least) supply implementations of the standard
Special requirement for pickling: A
A concrete subclass of tzinfo. utcoffset (dt)¶Return offset of local time from UTC, as a This represents the total offset from UTC; for example, if a return CONSTANT # fixed-offset class return CONSTANT + self.dst(dt) # daylight-aware class If The default implementation of
Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes. tzinfo. dst (dt)¶Return the daylight saving time (DST) adjustment, as a Return An instance tz of a
must return the same result for every Most implementations of
def dst(self, dt): # a fixed-offset class: doesn't account for DST return timedelta(0) or: def dst(self, dt): # Code to set dston and dstoff to the time zone's DST # transition times based on the input dt.year, and expressed # in standard local time. if dston <= dt.replace(tzinfo=None) < dstoff: return timedelta(hours=1) else: return timedelta(0) The default implementation of Changed in version 3.7: The DST offset is not restricted to a whole number of minutes. tzinfo. tzname (dt)¶Return the time zone name corresponding to the The default implementation of
These methods are called by a When When a
There is one more
tzinfo. fromutc (dt)¶This is called from the default
Most Skipping code for error cases, the default def fromutc(self, dt): # raise ValueError error if dt.tzinfo is not self dtoff = dt.utcoffset() dtdst = dt.dst() # raise ValueError if dtoff is None or dtdst is None delta = dtoff - dtdst # this is self's standard offset if delta: dt += delta # convert to standard local time dtdst = dt.dst() # raise ValueError if dtdst is None if dtdst: return dt + dtdst else: return dt In the following from datetime import tzinfo, timedelta, datetime ZERO = timedelta(0) HOUR = timedelta(hours=1) SECOND = timedelta(seconds=1) # A class capturing the platform's idea of local time. # (May result in wrong values on historical times in # timezones where UTC offset and/or the DST rules had # changed in the past.) import time as _time STDOFFSET = timedelta(seconds = -_time.timezone) if _time.daylight: DSTOFFSET = timedelta(seconds = -_time.altzone) else: DSTOFFSET = STDOFFSET DSTDIFF = DSTOFFSET - STDOFFSET class LocalTimezone(tzinfo): def fromutc(self, dt): assert dt.tzinfo is self stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND args = _time.localtime(stamp)[:6] dst_diff = DSTDIFF // SECOND # Detect fold fold = (args == _time.localtime(stamp - dst_diff)) return datetime(*args, microsecond=dt.microsecond, tzinfo=self, fold=fold) def utcoffset(self, dt): if self._isdst(dt): return DSTOFFSET else: return STDOFFSET def dst(self, dt): if self._isdst(dt): return DSTDIFF else: return ZERO def tzname(self, dt): return _time.tzname[self._isdst(dt)] def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) stamp = _time.mktime(tt) tt = _time.localtime(stamp) return tt.tm_isdst > 0 Local = LocalTimezone() # A complete implementation of current DST rules for major US time zones. def first_sunday_on_or_after(dt): days_to_go = 6 - dt.weekday() if days_to_go: dt += timedelta(days_to_go) return dt # US DST Rules # # This is a simplified (i.e., wrong for a few cases) set of rules for US # DST start and end times. For a complete and up-to-date set of DST rules # and timezone definitions, visit the Olson Database (or try pytz): # http://www.twinsun.com/tz/tz-link.htm # http://sourceforge.net/projects/pytz/ (might not be up-to-date) # # In the US, since 2007, DST starts at 2am (standard time) on the second # Sunday in March, which is the first Sunday on or after Mar 8. DSTSTART_2007 = datetime(1, 3, 8, 2) # and ends at 2am (DST time) on the first Sunday of Nov. DSTEND_2007 = datetime(1, 11, 1, 2) # From 1987 to 2006, DST used to start at 2am (standard time) on the first # Sunday in April and to end at 2am (DST time) on the last # Sunday of October, which is the first Sunday on or after Oct 25. DSTSTART_1987_2006 = datetime(1, 4, 1, 2) DSTEND_1987_2006 = datetime(1, 10, 25, 2) # From 1967 to 1986, DST used to start at 2am (standard time) on the last # Sunday in April (the one on or after April 24) and to end at 2am (DST time) # on the last Sunday of October, which is the first Sunday # on or after Oct 25. DSTSTART_1967_1986 = datetime(1, 4, 24, 2) DSTEND_1967_1986 = DSTEND_1987_2006 def us_dst_range(year): # Find start and end times for US DST. For years before 1967, return # start = end for no DST. if 2006 < year: dststart, dstend = DSTSTART_2007, DSTEND_2007 elif 1986 < year < 2007: dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 elif 1966 < year < 1987: dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 else: return (datetime(year, 1, 1), ) * 2 start = first_sunday_on_or_after(dststart.replace(year=year)) end = first_sunday_on_or_after(dstend.replace(year=year)) return start, end class USTimeZone(tzinfo): def __init__(self, hours, reprname, stdname, dstname): self.stdoffset = timedelta(hours=hours) self.reprname = reprname self.stdname = stdname self.dstname = dstname def __repr__(self): return self.reprname def tzname(self, dt): if self.dst(dt): return self.dstname else: return self.stdname def utcoffset(self, dt): return self.stdoffset + self.dst(dt) def dst(self, dt): if dt is None or dt.tzinfo is None: # An exception may be sensible here, in one or both cases. # It depends on how you want to treat them. The default # fromutc() implementation (called by the default astimezone() # implementation) passes a datetime with dt.tzinfo is self. return ZERO assert dt.tzinfo is self start, end = us_dst_range(dt.year) # Can't compare naive to aware objects, so strip the timezone from # dt first. dt = dt.replace(tzinfo=None) if start + HOUR <= dt < end - HOUR: # DST is in effect. return HOUR if end - HOUR <= dt < end: # Fold (an ambiguous hour): use dt.fold to disambiguate. return ZERO if dt.fold else HOUR if start <= dt < start + HOUR: # Gap (a non-existent hour): reverse the fold rule. return HOUR if dt.fold else ZERO # DST is off. return ZERO def fromutc(self, dt): assert dt.tzinfo is self start, end = us_dst_range(dt.year) start = start.replace(tzinfo=self) end = end.replace(tzinfo=self) std_time = dt + self.stdoffset dst_time = std_time + HOUR if end <= dst_time < end + HOUR: # Repeated hour return std_time.replace(fold=1) if std_time < start or dst_time >= end: # Standard time return std_time if start <= std_time < end - HOUR: # Daylight saving time return dst_time Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") Central = USTimeZone(-6, "Central", "CST", "CDT") Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") Note that there are unavoidable subtleties twice per year in a
UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM When DST starts (the “start” line), the local wall clock leaps
from 1:59 to 3:00. A wall time of the form 2:MM doesn’t really make sense on that day, so >>> from datetime import datetime, timezone >>> from tzinfo_examples import HOUR, Eastern >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc) >>> for i in range(4): ... u = u0 + i*HOUR ... t = u.astimezone(Eastern) ... print(u.time(), 'UTC =', t.time(), t.tzname()) ... 05:00:00 UTC = 00:00:00 EST 06:00:00 UTC = 01:00:00 EST 07:00:00 UTC = 03:00:00 EDT 08:00:00 UTC = 04:00:00 EDT When DST ends (the “end” line), there’s a potentially worse problem: there’s an hour that can’t be spelled unambiguously in local wall time: the last hour of daylight time. In Eastern, that’s times of the form 5:MM UTC on the day daylight time ends. The
local wall clock leaps from 1:59 (daylight time) back to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc) >>> for i in range(4): ... u = u0 + i*HOUR ... t = u.astimezone(Eastern) ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold) ... 04:00:00 UTC = 00:00:00 EDT 0 05:00:00 UTC = 01:00:00 EDT 0 06:00:00 UTC = 01:00:00 EST 1 07:00:00 UTC = 02:00:00 EST 0 Note that the Applications that can’t bear wall-time ambiguities should explicitly check the value of the See also IANA timezone database The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe. It is updated periodically to reflect changes made by political bodies to time zone boundaries, UTC offsets, and daylight-saving rules. timezone Objects¶The Objects of this class cannot be used to represent timezone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time. classdatetime. timezone (offset, name=None)¶The offset argument must be specified as a The name argument is optional. If specified it must be a string that will be used as the value returned by the
New in version 3.2. Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes. timezone. utcoffset (dt)¶Return the fixed value specified when the The dt argument is ignored. The
return value is a Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes. timezone. tzname (dt)¶Return the fixed value specified when the If name is not provided in the
constructor, the name returned by Changed in version 3.6: Name generated from timezone. dst (dt)¶Always returns timezone. fromutc (dt)¶Return Class attributes: timezone. utc ¶The UTC timezone, strftime() and strptime() Behavior¶
Conversely, the The table below provides a high-level comparison of
strftime() and strptime() Format Codes¶The following is a list of all the format codes that the 1989 C standard requires, and these work on all platforms with a standard C implementation.
Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values.
These may not be available on all platforms when used with the The full set of format codes supported varies across platforms,
because Python calls the platform C library’s New in version 3.6: Technical Detail¶Broadly speaking, For the
Using datetime(*(time.strptime(date_string, format)[0:6])) except when the format includes sub-second components or
timezone offset information, which are supported in For For For the same reason, handling of format strings containing Unicode code points that can’t be represented in the charset of the current locale is also platform-dependent. On some platforms such code points are preserved intact in the output, while on others Notes:
Footnotes 1If, that is, we ignore the effects of Relativity 2This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book Calendrical Calculations, where it’s the base calendar for all computations. See the book for algorithms for converting between proleptic Gregorian ordinals and many other calendar systems. 3See R. H. van Gent’s guide to the mathematics of the ISO 8601 calendar for a good explanation. 4Passing How do you write days in Python?Pandas Timestamp Method to Get the Name of the Day in Python
First, pass the date in YYYY-MM-DD format as its parameter. Next, use the dayofweek() and day_name() method to get the weekday number and name.
How do you define a day in Python?To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.
How do I use dates in Python?Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.
How do you get working days in Python?Get business days (weekdays) between two dates without numpy. First, iterate from the start date to the end date by one day using a for loop and range() function.. Use the weekday() function to check if the day is weekday or weekend.. If it is a weekday, then add it to the count.. Print the final count.. |