DateTimes¶
In this exercise we'll refresh ourselves on some basic variable handling and working with modules.
I'd like you to use the datetime
object from the datetime
module (yes, they have the same name and that's confusing).
Here's an example of using it...
# We can initialize datetime objects by passing the arguments year, month, and day. Optionally we can pass hour, minute and second as well.
hp_birthday = datetime(1980, 7, 31)
today = datetime(2024, 7, 1)
# Subtracting two datetimes returns a timedelta object
hp_alive = now - hp_birthday
isinstance(hp_alive, timedelta) # => True
# total_seconds is a method of the timedelta object that returns the total number of seconds between these two
hp_seconds_alive = hp_alive.total_seconds()
# We can also intialized timedeltas and add them to datetimes
hp_birthday + timedelta(days=10000)
You can read more about the datetime library in the datetime module: https://docs.python.org/3/library/datetime.html
Assignment¶
Using the above information:
- Write a function which takes someone's birthday as arguments (year, month and day) and returns the date, as a string, that they'll turn 10,000 days old.
- Write a function that calculates how many days old you are today.
Extra
- Calculate every year your birthday will fall on a Saturday night.
- If they average life expantancy for men is 73 years and the average life expectancy for women is 79 years, write a function that, given their birthday and gender, calculates the day that they should have their "mid-life crisis".
In [20]:
Copied!
from datetime import datetime
from datetime import timedelta
def when_10k_days_old(year, month, day):
birthday_dt = datetime(year, month, day)
when_10k_dt = birthday_dt + timedelta(days=10000)
when_10k_str = f"{when_10k_dt.month}/{when_10k_dt.day}/{when_10k_dt.year}"
return when_10k_str
def how_old_in_days(birth_year, birth_month, birth_day):
birthday_dt = datetime(birth_year, birth_month, birth_day)
today_dt = datetime.today()
age_td = today_dt - birthday_dt
age_days = age_td.days
return age_days
def which_years_will_be_saturday(birth_year, birth_month, birth_day):
bd_dt = datetime(birth_year, birth_month, birth_day)
today_dt = datetime.today()
saturday_birthday_dts = []
while bd_dt < today_dt:
bd_dt = datetime(bd_dt.year + 1, bd_dt.month, bd_dt.day)
if bd_dt.weekday() == 5: # Saturday
saturday_birthday_dts.append(bd_dt)
return saturday_birthday_dts
def midlife_crisis(birth_year, birth_month, birth_day, gender):
bd_dt = datetime(birth_year, birth_month, birth_day)
if gender == "man":
death_dt = datetime(birth_year + 73, birth_month, birth_day)
else:
death_dt = datetime(birth_year + 79, birth_month, birth_day)
life_expect_td = death_dt - bd_dt
half_life_expect_days = life_expect_td.days // 2
midlife_crisis_dt = bd_dt + timedelta(days=half_life_expect_days)
return midlife_crisis_dt
when_10k_days_old(1980, 7, 31)
how_old_in_days(1980, 7, 31)
which_years_will_be_saturday(1980, 7, 31)
midlife_crisis(1980, 7, 31, "man")
from datetime import datetime
from datetime import timedelta
def when_10k_days_old(year, month, day):
birthday_dt = datetime(year, month, day)
when_10k_dt = birthday_dt + timedelta(days=10000)
when_10k_str = f"{when_10k_dt.month}/{when_10k_dt.day}/{when_10k_dt.year}"
return when_10k_str
def how_old_in_days(birth_year, birth_month, birth_day):
birthday_dt = datetime(birth_year, birth_month, birth_day)
today_dt = datetime.today()
age_td = today_dt - birthday_dt
age_days = age_td.days
return age_days
def which_years_will_be_saturday(birth_year, birth_month, birth_day):
bd_dt = datetime(birth_year, birth_month, birth_day)
today_dt = datetime.today()
saturday_birthday_dts = []
while bd_dt < today_dt:
bd_dt = datetime(bd_dt.year + 1, bd_dt.month, bd_dt.day)
if bd_dt.weekday() == 5: # Saturday
saturday_birthday_dts.append(bd_dt)
return saturday_birthday_dts
def midlife_crisis(birth_year, birth_month, birth_day, gender):
bd_dt = datetime(birth_year, birth_month, birth_day)
if gender == "man":
death_dt = datetime(birth_year + 73, birth_month, birth_day)
else:
death_dt = datetime(birth_year + 79, birth_month, birth_day)
life_expect_td = death_dt - bd_dt
half_life_expect_days = life_expect_td.days // 2
midlife_crisis_dt = bd_dt + timedelta(days=half_life_expect_days)
return midlife_crisis_dt
when_10k_days_old(1980, 7, 31)
how_old_in_days(1980, 7, 31)
which_years_will_be_saturday(1980, 7, 31)
midlife_crisis(1980, 7, 31, "man")
Out[20]:
datetime.datetime(2017, 1, 29, 0, 0)
In [10]:
Copied!
dt = datetime(1980, 7, 31)
dt.weekday()
dt = datetime(1980, 7, 31)
dt.weekday()
Out[10]:
3
In [25]:
Copied!
import pandas as pd
help(pd.Timestamp)
import pandas as pd
help(pd.Timestamp)
Help on class Timestamp in module pandas._libs.tslibs.timestamps: class Timestamp(_Timestamp) | Timestamp(ts_input=<object object at 0x7aeb7e930be0>, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, nanosecond=None, tz=None, unit=None, fold=None) | | Pandas replacement for python datetime.datetime object. | | Timestamp is the pandas equivalent of python's Datetime | and is interchangeable with it in most cases. It's the type used | for the entries that make up a DatetimeIndex, and other timeseries | oriented data structures in pandas. | | Parameters | ---------- | ts_input : datetime-like, str, int, float | Value to be converted to Timestamp. | year, month, day : int | hour, minute, second, microsecond : int, optional, default 0 | tzinfo : datetime.tzinfo, optional, default None | nanosecond : int, optional, default 0 | tz : str, pytz.timezone, dateutil.tz.tzfile or None | Time zone for time which Timestamp will have. | unit : str | Unit used for conversion if ts_input is of type int or float. The | valid values are 'D', 'h', 'm', 's', 'ms', 'us', and 'ns'. For | example, 's' means seconds and 'ms' means milliseconds. | | For float inputs, the result will be stored in nanoseconds, and | the unit attribute will be set as ``'ns'``. | fold : {0, 1}, default None, keyword-only | Due to daylight saving time, one wall clock time can occur twice | when shifting from summer to winter time; fold describes whether the | datetime-like corresponds to the first (0) or the second time (1) | the wall clock hits the ambiguous time. | | .. versionadded:: 1.1.0 | | Notes | ----- | There are essentially three calling conventions for the constructor. The | primary form accepts four parameters. They can be passed by position or | keyword. | | The other two forms mimic the parameters from ``datetime.datetime``. They | can be passed by either position or keyword, but not both mixed together. | | Examples | -------- | Using the primary calling convention: | | This converts a datetime-like string | | >>> pd.Timestamp('2017-01-01T12') | Timestamp('2017-01-01 12:00:00') | | This converts a float representing a Unix epoch in units of seconds | | >>> pd.Timestamp(1513393355.5, unit='s') | Timestamp('2017-12-16 03:02:35.500000') | | This converts an int representing a Unix-epoch in units of seconds | and for a particular timezone | | >>> pd.Timestamp(1513393355, unit='s', tz='US/Pacific') | Timestamp('2017-12-15 19:02:35-0800', tz='US/Pacific') | | Using the other two forms that mimic the API for ``datetime.datetime``: | | >>> pd.Timestamp(2017, 1, 1, 12) | Timestamp('2017-01-01 12:00:00') | | >>> pd.Timestamp(year=2017, month=1, day=1, hour=12) | Timestamp('2017-01-01 12:00:00') | | Method resolution order: | Timestamp | _Timestamp | pandas._libs.tslibs.base.ABCTimestamp | datetime.datetime | datetime.date | builtins.object | | Methods defined here: | | __new__(cls, ts_input=<object object at 0x7aeb7e930be0>, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, nanosecond=None, tz=None, unit=None, fold=None) | | astimezone = tz_convert(self, tz) | | ceil(self, freq, ambiguous='raise', nonexistent='raise') | Return a new Timestamp ceiled to this resolution. | | Parameters | ---------- | freq : str | Frequency string indicating the ceiling resolution. | ambiguous : bool or {'raise', 'NaT'}, default 'raise' | The behavior is as follows: | | * bool contains flags to determine if time is dst or not (note | that this flag is only applicable for ambiguous fall dst dates). | * 'NaT' will return NaT for an ambiguous time. | * 'raise' will raise an AmbiguousTimeError for an ambiguous time. | | nonexistent : {'raise', 'shift_forward', 'shift_backward, 'NaT', timedelta}, default 'raise' | A nonexistent time does not exist in a particular timezone | where clocks moved forward due to DST. | | * 'shift_forward' will shift the nonexistent time forward to the | closest existing time. | * 'shift_backward' will shift the nonexistent time backward to the | closest existing time. | * 'NaT' will return NaT where there are nonexistent times. | * timedelta objects will shift nonexistent times by the timedelta. | * 'raise' will raise an NonExistentTimeError if there are | nonexistent times. | | Raises | ------ | ValueError if the freq cannot be converted. | | Notes | ----- | If the Timestamp has a timezone, ceiling will take place relative to the | local ("wall") time and re-localized to the same timezone. When ceiling | near daylight savings time, use ``nonexistent`` and ``ambiguous`` to | control the re-localization behavior. | | Examples | -------- | Create a timestamp object: | | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | | A timestamp can be ceiled using multiple frequency units: | | >>> ts.ceil(freq='H') # hour | Timestamp('2020-03-14 16:00:00') | | >>> ts.ceil(freq='T') # minute | Timestamp('2020-03-14 15:33:00') | | >>> ts.ceil(freq='S') # seconds | Timestamp('2020-03-14 15:32:53') | | >>> ts.ceil(freq='U') # microseconds | Timestamp('2020-03-14 15:32:52.192549') | | ``freq`` can also be a multiple of a single unit, like '5T' (i.e. 5 minutes): | | >>> ts.ceil(freq='5T') | Timestamp('2020-03-14 15:35:00') | | or a combination of multiple units, like '1H30T' (i.e. 1 hour and 30 minutes): | | >>> ts.ceil(freq='1H30T') | Timestamp('2020-03-14 16:30:00') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.ceil() | NaT | | When rounding near a daylight savings time transition, use ``ambiguous`` or | ``nonexistent`` to control how the timestamp should be re-localized. | | >>> ts_tz = pd.Timestamp("2021-10-31 01:30:00").tz_localize("Europe/Amsterdam") | | >>> ts_tz.ceil("H", ambiguous=False) | Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') | | >>> ts_tz.ceil("H", ambiguous=True) | Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') | | floor(self, freq, ambiguous='raise', nonexistent='raise') | Return a new Timestamp floored to this resolution. | | Parameters | ---------- | freq : str | Frequency string indicating the flooring resolution. | ambiguous : bool or {'raise', 'NaT'}, default 'raise' | The behavior is as follows: | | * bool contains flags to determine if time is dst or not (note | that this flag is only applicable for ambiguous fall dst dates). | * 'NaT' will return NaT for an ambiguous time. | * 'raise' will raise an AmbiguousTimeError for an ambiguous time. | | nonexistent : {'raise', 'shift_forward', 'shift_backward, 'NaT', timedelta}, default 'raise' | A nonexistent time does not exist in a particular timezone | where clocks moved forward due to DST. | | * 'shift_forward' will shift the nonexistent time forward to the | closest existing time. | * 'shift_backward' will shift the nonexistent time backward to the | closest existing time. | * 'NaT' will return NaT where there are nonexistent times. | * timedelta objects will shift nonexistent times by the timedelta. | * 'raise' will raise an NonExistentTimeError if there are | nonexistent times. | | Raises | ------ | ValueError if the freq cannot be converted. | | Notes | ----- | If the Timestamp has a timezone, flooring will take place relative to the | local ("wall") time and re-localized to the same timezone. When flooring | near daylight savings time, use ``nonexistent`` and ``ambiguous`` to | control the re-localization behavior. | | Examples | -------- | Create a timestamp object: | | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | | A timestamp can be floored using multiple frequency units: | | >>> ts.floor(freq='H') # hour | Timestamp('2020-03-14 15:00:00') | | >>> ts.floor(freq='T') # minute | Timestamp('2020-03-14 15:32:00') | | >>> ts.floor(freq='S') # seconds | Timestamp('2020-03-14 15:32:52') | | >>> ts.floor(freq='N') # nanoseconds | Timestamp('2020-03-14 15:32:52.192548651') | | ``freq`` can also be a multiple of a single unit, like '5T' (i.e. 5 minutes): | | >>> ts.floor(freq='5T') | Timestamp('2020-03-14 15:30:00') | | or a combination of multiple units, like '1H30T' (i.e. 1 hour and 30 minutes): | | >>> ts.floor(freq='1H30T') | Timestamp('2020-03-14 15:00:00') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.floor() | NaT | | When rounding near a daylight savings time transition, use ``ambiguous`` or | ``nonexistent`` to control how the timestamp should be re-localized. | | >>> ts_tz = pd.Timestamp("2021-10-31 03:30:00").tz_localize("Europe/Amsterdam") | | >>> ts_tz.floor("2H", ambiguous=False) | Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') | | >>> ts_tz.floor("2H", ambiguous=True) | Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') | | isoweekday(self) | Return the day of the week represented by the date. | | Monday == 1 ... Sunday == 7. | | replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, nanosecond=None, tzinfo=<class 'object'>, fold=None) | Implements datetime.replace, handles nanoseconds. | | Parameters | ---------- | year : int, optional | month : int, optional | day : int, optional | hour : int, optional | minute : int, optional | second : int, optional | microsecond : int, optional | nanosecond : int, optional | tzinfo : tz-convertible, optional | fold : int, optional | | Returns | ------- | Timestamp with fields replaced | | Examples | -------- | Create a timestamp object: | | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651', tz='UTC') | >>> ts | Timestamp('2020-03-14 15:32:52.192548651+0000', tz='UTC') | | Replace year and the hour: | | >>> ts.replace(year=1999, hour=10) | Timestamp('1999-03-14 10:32:52.192548651+0000', tz='UTC') | | Replace timezone (not a conversion): | | >>> import pytz | >>> ts.replace(tzinfo=pytz.timezone('US/Pacific')) | Timestamp('2020-03-14 15:32:52.192548651-0700', tz='US/Pacific') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.replace(tzinfo=pytz.timezone('US/Pacific')) | NaT | | round(self, freq, ambiguous='raise', nonexistent='raise') | Round the Timestamp to the specified resolution. | | Parameters | ---------- | freq : str | Frequency string indicating the rounding resolution. | ambiguous : bool or {'raise', 'NaT'}, default 'raise' | The behavior is as follows: | | * bool contains flags to determine if time is dst or not (note | that this flag is only applicable for ambiguous fall dst dates). | * 'NaT' will return NaT for an ambiguous time. | * 'raise' will raise an AmbiguousTimeError for an ambiguous time. | | nonexistent : {'raise', 'shift_forward', 'shift_backward, 'NaT', timedelta}, default 'raise' | A nonexistent time does not exist in a particular timezone | where clocks moved forward due to DST. | | * 'shift_forward' will shift the nonexistent time forward to the | closest existing time. | * 'shift_backward' will shift the nonexistent time backward to the | closest existing time. | * 'NaT' will return NaT where there are nonexistent times. | * timedelta objects will shift nonexistent times by the timedelta. | * 'raise' will raise an NonExistentTimeError if there are | nonexistent times. | | Returns | ------- | a new Timestamp rounded to the given resolution of `freq` | | Raises | ------ | ValueError if the freq cannot be converted | | Notes | ----- | If the Timestamp has a timezone, rounding will take place relative to the | local ("wall") time and re-localized to the same timezone. When rounding | near daylight savings time, use ``nonexistent`` and ``ambiguous`` to | control the re-localization behavior. | | Examples | -------- | Create a timestamp object: | | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | | A timestamp can be rounded using multiple frequency units: | | >>> ts.round(freq='H') # hour | Timestamp('2020-03-14 16:00:00') | | >>> ts.round(freq='T') # minute | Timestamp('2020-03-14 15:33:00') | | >>> ts.round(freq='S') # seconds | Timestamp('2020-03-14 15:32:52') | | >>> ts.round(freq='L') # milliseconds | Timestamp('2020-03-14 15:32:52.193000') | | ``freq`` can also be a multiple of a single unit, like '5T' (i.e. 5 minutes): | | >>> ts.round(freq='5T') | Timestamp('2020-03-14 15:35:00') | | or a combination of multiple units, like '1H30T' (i.e. 1 hour and 30 minutes): | | >>> ts.round(freq='1H30T') | Timestamp('2020-03-14 15:00:00') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.round() | NaT | | When rounding near a daylight savings time transition, use ``ambiguous`` or | ``nonexistent`` to control how the timestamp should be re-localized. | | >>> ts_tz = pd.Timestamp("2021-10-31 01:30:00").tz_localize("Europe/Amsterdam") | | >>> ts_tz.round("H", ambiguous=False) | Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') | | >>> ts_tz.round("H", ambiguous=True) | Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') | | strftime(self, format) | Return a formatted string of the Timestamp. | | Parameters | ---------- | format : str | Format string to convert Timestamp to string. | See strftime documentation for more information on the format string: | https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior. | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> ts.strftime('%Y-%m-%d %X') | '2020-03-14 15:32:52' | | to_julian_date(self) -> numpy.float64 | Convert TimeStamp to a Julian Date. | | 0 Julian date is noon January 1, 4713 BC. | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52') | >>> ts.to_julian_date() | 2458923.147824074 | | tz_convert(self, tz) | Convert timezone-aware Timestamp to another time zone. | | Parameters | ---------- | tz : str, pytz.timezone, dateutil.tz.tzfile or None | Time zone for time which Timestamp will be converted to. | None will remove timezone holding UTC time. | | Returns | ------- | converted : Timestamp | | Raises | ------ | TypeError | If Timestamp is tz-naive. | | Examples | -------- | Create a timestamp object with UTC timezone: | | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651', tz='UTC') | >>> ts | Timestamp('2020-03-14 15:32:52.192548651+0000', tz='UTC') | | Change to Tokyo timezone: | | >>> ts.tz_convert(tz='Asia/Tokyo') | Timestamp('2020-03-15 00:32:52.192548651+0900', tz='Asia/Tokyo') | | Can also use ``astimezone``: | | >>> ts.astimezone(tz='Asia/Tokyo') | Timestamp('2020-03-15 00:32:52.192548651+0900', tz='Asia/Tokyo') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.tz_convert(tz='Asia/Tokyo') | NaT | | tz_localize(self, tz, ambiguous='raise', nonexistent='raise') | Localize the Timestamp to a timezone. | | Convert naive Timestamp to local time zone or remove | timezone from timezone-aware Timestamp. | | Parameters | ---------- | tz : str, pytz.timezone, dateutil.tz.tzfile or None | Time zone for time which Timestamp will be converted to. | None will remove timezone holding local time. | | ambiguous : bool, 'NaT', default 'raise' | When clocks moved backward due to DST, ambiguous times may arise. | For example in Central European Time (UTC+01), when going from | 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at | 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the | `ambiguous` parameter dictates how ambiguous times should be | handled. | | The behavior is as follows: | | * bool contains flags to determine if time is dst or not (note | that this flag is only applicable for ambiguous fall dst dates). | * 'NaT' will return NaT for an ambiguous time. | * 'raise' will raise an AmbiguousTimeError for an ambiguous time. | | nonexistent : 'shift_forward', 'shift_backward, 'NaT', timedelta, default 'raise' | A nonexistent time does not exist in a particular timezone | where clocks moved forward due to DST. | | The behavior is as follows: | | * 'shift_forward' will shift the nonexistent time forward to the | closest existing time. | * 'shift_backward' will shift the nonexistent time backward to the | closest existing time. | * 'NaT' will return NaT where there are nonexistent times. | * timedelta objects will shift nonexistent times by the timedelta. | * 'raise' will raise an NonExistentTimeError if there are | nonexistent times. | | Returns | ------- | localized : Timestamp | | Raises | ------ | TypeError | If the Timestamp is tz-aware and tz is not None. | | Examples | -------- | Create a naive timestamp object: | | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> ts | Timestamp('2020-03-14 15:32:52.192548651') | | Add 'Europe/Stockholm' as timezone: | | >>> ts.tz_localize(tz='Europe/Stockholm') | Timestamp('2020-03-14 15:32:52.192548651+0100', tz='Europe/Stockholm') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.tz_localize() | NaT | | weekday(self) | Return the day of the week represented by the date. | | Monday == 0 ... Sunday == 6. | | ---------------------------------------------------------------------- | Class methods defined here: | | combine(date, time) from builtins.type | Timestamp.combine(date, time) | | Combine date, time into datetime with same date and time fields. | | Examples | -------- | >>> from datetime import date, time | >>> pd.Timestamp.combine(date(2020, 3, 14), time(15, 30, 15)) | Timestamp('2020-03-14 15:30:15') | | fromordinal(ordinal, tz=None) from builtins.type | Construct a timestamp from a a proleptic Gregorian ordinal. | | Parameters | ---------- | ordinal : int | Date corresponding to a proleptic Gregorian ordinal. | tz : str, pytz.timezone, dateutil.tz.tzfile or None | Time zone for the Timestamp. | | Notes | ----- | By definition there cannot be any tz info on the ordinal itself. | | Examples | -------- | >>> pd.Timestamp.fromordinal(737425) | Timestamp('2020-01-01 00:00:00') | | fromtimestamp(ts, tz=None) from builtins.type | Timestamp.fromtimestamp(ts) | | Transform timestamp[, tz] to tz's local time from POSIX timestamp. | | Examples | -------- | >>> pd.Timestamp.fromtimestamp(1584199972) # doctest: +SKIP | Timestamp('2020-03-14 15:32:52') | | Note that the output may change depending on your local time. | | now(tz=None) from builtins.type | Return new Timestamp object representing current time local to tz. | | Parameters | ---------- | tz : str or timezone object, default None | Timezone to localize to. | | Examples | -------- | >>> pd.Timestamp.now() # doctest: +SKIP | Timestamp('2020-11-16 22:06:16.378782') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.now() | NaT | | strptime(date_string, format) from builtins.type | Timestamp.strptime(string, format) | | Function is not implemented. Use pd.to_datetime(). | | today(tz=None) from builtins.type | Return the current time in the local timezone. | | This differs from datetime.today() in that it can be localized to a | passed timezone. | | Parameters | ---------- | tz : str or timezone object, default None | Timezone to localize to. | | Examples | -------- | >>> pd.Timestamp.today() # doctest: +SKIP | Timestamp('2020-11-16 22:37:39.969883') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.today() | NaT | | utcfromtimestamp(ts) from builtins.type | Timestamp.utcfromtimestamp(ts) | | Construct a timezone-aware UTC datetime from a POSIX timestamp. | | Notes | ----- | Timestamp.utcfromtimestamp behavior differs from datetime.utcfromtimestamp | in returning a timezone-aware object. | | Examples | -------- | >>> pd.Timestamp.utcfromtimestamp(1584199972) | Timestamp('2020-03-14 15:32:52+0000', tz='UTC') | | utcnow() from builtins.type | Timestamp.utcnow() | | Return a new Timestamp representing UTC day and time. | | Examples | -------- | >>> pd.Timestamp.utcnow() # doctest: +SKIP | Timestamp('2020-11-16 22:50:18.092888+0000', tz='UTC') | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | daysinmonth | Return the number of days in the month. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.days_in_month | 31 | | tz | Alias for tzinfo. | | Examples | -------- | >>> ts = pd.Timestamp(1584226800, unit='s', tz='Europe/Stockholm') | >>> ts.tz | <DstTzInfo 'Europe/Stockholm' CET+1:00:00 STD> | | weekofyear | Return the week number of the year. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.week | 11 | | ---------------------------------------------------------------------- | Methods inherited from _Timestamp: | | __add__(self, value, /) | Return self+value. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __radd__(...) | Return value+self. | | __reduce__(...) | __reduce__() -> (cls, state) | | __reduce_ex__(...) | __reduce_ex__(proto) -> (cls, state) | | __repr__(self, /) | Return repr(self). | | __rsub__(...) | Return value-self. | | __setstate__(...) | | __sub__(self, value, /) | Return self-value. | | as_unit(...) | Convert the underlying int64 representaton to the given unit. | | Parameters | ---------- | unit : {"ns", "us", "ms", "s"} | round_ok : bool, default True | If False and the conversion requires rounding, raise. | | Returns | ------- | Timestamp | | day_name(...) | Return the day name of the Timestamp with specified locale. | | Parameters | ---------- | locale : str, default None (English locale) | Locale determining the language in which to return the day name. | | Returns | ------- | str | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> ts.day_name() | 'Saturday' | | Analogous for ``pd.NaT``: | | >>> pd.NaT.day_name() | nan | | isoformat(...) | Return the time formatted according to ISO 8610. | | The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmmnnn'. | By default, the fractional part is omitted if self.microsecond == 0 | and self.nanosecond == 0. | | If self.tzinfo is not None, the UTC offset is also attached, giving | giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmmnnn+HH:MM'. | | Parameters | ---------- | sep : str, default 'T' | String used as the separator between the date and time. | | timespec : str, default 'auto' | Specifies the number of additional terms of the time to include. | The valid values are 'auto', 'hours', 'minutes', 'seconds', | 'milliseconds', 'microseconds', and 'nanoseconds'. | | Returns | ------- | str | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> ts.isoformat() | '2020-03-14T15:32:52.192548651' | >>> ts.isoformat(timespec='microseconds') | '2020-03-14T15:32:52.192548' | | month_name(...) | Return the month name of the Timestamp with specified locale. | | Parameters | ---------- | locale : str, default None (English locale) | Locale determining the language in which to return the month name. | | Returns | ------- | str | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> ts.month_name() | 'March' | | Analogous for ``pd.NaT``: | | >>> pd.NaT.month_name() | nan | | normalize(...) | Normalize Timestamp to midnight, preserving tz information. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14, 15, 30) | >>> ts.normalize() | Timestamp('2020-03-14 00:00:00') | | timestamp(...) | Return POSIX timestamp as float. | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548') | >>> ts.timestamp() | 1584199972.192548 | | to_datetime64(...) | Return a numpy.datetime64 object with 'ns' precision. | | to_numpy(...) | Convert the Timestamp to a NumPy datetime64. | | This is an alias method for `Timestamp.to_datetime64()`. The dtype and | copy parameters are available here only for compatibility. Their values | will not affect the return value. | | Returns | ------- | numpy.datetime64 | | See Also | -------- | DatetimeIndex.to_numpy : Similar method for DatetimeIndex. | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> ts.to_numpy() | numpy.datetime64('2020-03-14T15:32:52.192548651') | | Analogous for ``pd.NaT``: | | >>> pd.NaT.to_numpy() | numpy.datetime64('NaT') | | to_period(...) | Return an period of which this timestamp is an observation. | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') | >>> # Year end frequency | >>> ts.to_period(freq='Y') | Period('2020', 'A-DEC') | | >>> # Month end frequency | >>> ts.to_period(freq='M') | Period('2020-03', 'M') | | >>> # Weekly frequency | >>> ts.to_period(freq='W') | Period('2020-03-09/2020-03-15', 'W-SUN') | | >>> # Quarter end frequency | >>> ts.to_period(freq='Q') | Period('2020Q1', 'Q-DEC') | | to_pydatetime(...) | Convert a Timestamp object to a native Python datetime object. | | If warn=True, issue a warning if nanoseconds is nonzero. | | Examples | -------- | >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548') | >>> ts.to_pydatetime() | datetime.datetime(2020, 3, 14, 15, 32, 52, 192548) | | Analogous for ``pd.NaT``: | | >>> pd.NaT.to_pydatetime() | NaT | | ---------------------------------------------------------------------- | Data descriptors inherited from _Timestamp: | | asm8 | Return numpy datetime64 format in nanoseconds. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14, 15) | >>> ts.asm8 | numpy.datetime64('2020-03-14T15:00:00.000000') | | day_of_week | Return day of the week. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.day_of_week | 5 | | day_of_year | Return the day of the year. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.day_of_year | 74 | | dayofweek | Return day of the week. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.day_of_week | 5 | | dayofyear | Return the day of the year. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.day_of_year | 74 | | days_in_month | Return the number of days in the month. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.days_in_month | 31 | | is_leap_year | Return True if year is a leap year. | | Returns | ------- | bool | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_leap_year | True | | is_month_end | Check if the date is the last day of the month. | | Returns | ------- | bool | True if the date is the last day of the month. | | See Also | -------- | Timestamp.is_month_start : Similar property indicating month start. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_month_end | False | | >>> ts = pd.Timestamp(2020, 12, 31) | >>> ts.is_month_end | True | | is_month_start | Check if the date is the first day of the month. | | Returns | ------- | bool | True if the date is the first day of the month. | | See Also | -------- | Timestamp.is_month_end : Similar property indicating the last day of the month. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_month_start | False | | >>> ts = pd.Timestamp(2020, 1, 1) | >>> ts.is_month_start | True | | is_quarter_end | Check if date is last day of the quarter. | | Returns | ------- | bool | True if date is last day of the quarter. | | See Also | -------- | Timestamp.is_quarter_start : Similar property indicating the quarter start. | Timestamp.quarter : Return the quarter of the date. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_quarter_end | False | | >>> ts = pd.Timestamp(2020, 3, 31) | >>> ts.is_quarter_end | True | | is_quarter_start | Check if the date is the first day of the quarter. | | Returns | ------- | bool | True if date is first day of the quarter. | | See Also | -------- | Timestamp.is_quarter_end : Similar property indicating the quarter end. | Timestamp.quarter : Return the quarter of the date. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_quarter_start | False | | >>> ts = pd.Timestamp(2020, 4, 1) | >>> ts.is_quarter_start | True | | is_year_end | Return True if date is last day of the year. | | Returns | ------- | bool | | See Also | -------- | Timestamp.is_year_start : Similar property indicating the start of the year. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_year_end | False | | >>> ts = pd.Timestamp(2020, 12, 31) | >>> ts.is_year_end | True | | is_year_start | Return True if date is first day of the year. | | Returns | ------- | bool | | See Also | -------- | Timestamp.is_year_end : Similar property indicating the end of the year. | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.is_year_start | False | | >>> ts = pd.Timestamp(2020, 1, 1) | >>> ts.is_year_start | True | | nanosecond | | quarter | Return the quarter of the year. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.quarter | 1 | | unit | The abbreviation associated with self._creso. | | Examples | -------- | >>> pd.Timestamp("2020-01-01 12:34:56").unit | 's' | | >>> pd.Timestamp("2020-01-01 12:34:56.123").unit | 'ms' | | >>> pd.Timestamp("2020-01-01 12:34:56.123456").unit | 'us' | | >>> pd.Timestamp("2020-01-01 12:34:56.123456789").unit | 'ns' | | value | | week | Return the week number of the year. | | Returns | ------- | int | | Examples | -------- | >>> ts = pd.Timestamp(2020, 3, 14) | >>> ts.week | 11 | | year | | ---------------------------------------------------------------------- | Data and other attributes inherited from _Timestamp: | | __array_priority__ = 100 | | __pyx_vtable__ = <capsule object NULL> | | max = Timestamp('2262-04-11 23:47:16.854775807') | | min = Timestamp('1677-09-21 00:12:43.145224193') | | resolution = Timedelta('0 days 00:00:00.000000001') | | ---------------------------------------------------------------------- | Methods inherited from pandas._libs.tslibs.base.ABCTimestamp: | | __reduce_cython__(...) | | __setstate_cython__(...) | | ---------------------------------------------------------------------- | Methods inherited from datetime.datetime: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __str__(self, /) | Return str(self). | | ctime(...) | Return ctime() style string. | | date(...) | Return date object with same year, month and day. | | dst(...) | Return self.tzinfo.dst(self). | | time(...) | Return time object with same time but with tzinfo=None. | | timetuple(...) | Return time tuple, compatible with time.localtime(). | | timetz(...) | Return time object with same time and tzinfo. | | tzname(...) | Return self.tzinfo.tzname(self). | | utcoffset(...) | Return self.tzinfo.utcoffset(self). | | utctimetuple(...) | Return UTC time tuple, compatible with time.localtime(). | | ---------------------------------------------------------------------- | Class methods inherited from datetime.datetime: | | fromisoformat(...) from builtins.type | string -> datetime from datetime.isoformat() output | | ---------------------------------------------------------------------- | Data descriptors inherited from datetime.datetime: | | fold | | hour | | microsecond | | minute | | second | | tzinfo | | ---------------------------------------------------------------------- | Methods inherited from datetime.date: | | __format__(...) | Formats self with strftime. | | isocalendar(...) | Return a named tuple containing ISO year, week number, and weekday. | | toordinal(...) | Return proleptic Gregorian ordinal. January 1 of year 1 is day 1. | | ---------------------------------------------------------------------- | Class methods inherited from datetime.date: | | fromisocalendar(...) from builtins.type | int, int, int -> Construct a date from the ISO year, week number and weekday. | | This is the inverse of the date.isocalendar() function | | ---------------------------------------------------------------------- | Data descriptors inherited from datetime.date: | | day | | month
In [ ]:
Copied!