<jupyter_start><jupyter_text>Python datetime moduleWe will look at an important standard library, the [datetime library][1] which contains many powerful functions to support date, time and datetime manipulation. Pandas does not rely on this object and instead creates its own, a `Timestamp`, discussed in other notebooks.The datetime library is part of the standard library, so it comes  shipped along with every Python installation. Let's get started by importing it into our namespace.[1]: https://docs.python.org/3/library/datetime.html<jupyter_code>import datetime<jupyter_output><empty_output><jupyter_text>Create a date, a time and a datetimeThe datetime module provides three separate objects for dates, times, and datetimes.  Let's use the `date` type to construct a date. It takes three integers, the year, month and day. Here we create the date April 11, 2016.<jupyter_code>my_date = datetime.date(2016, 4, 11)
my_date
type(my_date)<jupyter_output><empty_output><jupyter_text>Use the `time` type to construct a time. It takes 4 integers - hours, minutes, seconds, and microseconds (one millionth of a second). Here we create the time 10:54:32.034512<jupyter_code>my_time = datetime.time(10, 54, 32, 34512)
my_time
type(my_time)<jupyter_output><empty_output><jupyter_text>Only the hour component is mandatory. For instance, we can create the time 5:44 with this:<jupyter_code>datetime.time(5, 44)<jupyter_output><empty_output><jupyter_text>Or you can specify just a particular component of time.<jupyter_code>datetime.time(second=34)<jupyter_output><empty_output><jupyter_text>Finally, we can construct a datetime with the `datetime` type, which takes up to 7 parameters - three for the date, and four for the time.<jupyter_code>my_datetime = datetime.datetime(2016, 4, 11, 10, 54, 32, 34512)
my_datetime
type(my_datetime)<jupyter_output><empty_output><jupyter_text>Format changes when printed to the screenPrinting the objects from above to the screen provides a more readable view.<jupyter_code>print(my_date)
print(my_time)
print(my_datetime)<jupyter_output><empty_output><jupyter_text>Attributes of date, time, and datetimesEach individual component of the date, time, and datetime is available as an attribute.<jupyter_code>my_date.year
my_date.month
my_date.day
my_time.hour
my_time.minute
my_time.second
my_datetime.day
my_datetime.microsecond
my_date.weekday()<jupyter_output><empty_output><jupyter_text>Methods of date, time, and datetimesSeveral methods exist for each of these objects. The methods that begin with ISO represent the [International Standards Organization][1] formatting rules for dates, times, and datetimes. The particular standard here is [ISO 8601][2]. Python will return according to this standard.[1]: https://www.iso.org/home.html[2]: https://en.wikipedia.org/wiki/ISO_8601<jupyter_code>my_date.weekday()
my_date.isoformat()
my_date.isocalendar()
my_time.isoformat()
my_datetime.isoformat()
# get the date from a datetime
my_datetime.date()
# get the time from a datetime
my_datetime.time()<jupyter_output><empty_output><jupyter_text>Alternate ConstructorsYou can create dates and datetimes from a single integer which represents the number of seconds since the Unix epoch, January 1, 1970 UTC. UTC is the timezone, [Coordinated Universal Time][1] and is 0 degrees longitude or 5 hours ahead of Easter Standard Time.Passing the integer 0 to the `fromtimestamp` datetime constructor will return a datetime at the Unix epoch adjusted to your local timezone. If you are located in EST, then you will get returned December 31, 1969 7 p.m.[1]: https://en.wikipedia.org/wiki/Coordinated_Universal_Time<jupyter_code>datetime.datetime.fromtimestamp(0)
# 1 billion seconds from the unix epoch
datetime.datetime.fromtimestamp(10 ** 9)<jupyter_output><empty_output><jupyter_text>The date type also has this constructor, but not time.<jupyter_code># also works for date
datetime.date.fromtimestamp(10 ** 9)<jupyter_output><empty_output><jupyter_text>Can get todays date or datetime:<jupyter_code>datetime.date.today()
datetime.datetime.now()<jupyter_output><empty_output><jupyter_text>Constructing from stringsThe `strptime` alternate datetime constructor has the ability to convert a string into a datetime. In addition to the string, you must pass it a specific **format** to alert the constructor which part of the string corresponds to which component of the datetime. There are special character codes called **directives** which must be used to form this correspondence. DirectivesAll the directives can be found in the official [Python documentation for the datetime module][1]. Below are some common ones.* **%y** - two digit year* **%Y** - four digit year* **%m** - Month* **%d** - Day of the month * **%H** - Hour (24-hour clock)* **%I** - Hour (12-hour clock)* **%M** - Minute[1]: https://docs.python.org/3/library/datetime.htmlstrftime-strptime-behavior  Examples of string parsing to datetimesThe `strptime` alternate constructor stands for string parse time (though it only parses datetimes). You must create a string with the correct directives that represents the format of the date string you are trying to convert to a datetime. For instance, the string '2016-10-22' can use the format '%Y-%m-%d' to parse it correctly.<jupyter_code>s = '2016-10-22'
fmt = '%Y-%m-%d'
datetime.datetime.strptime(s, fmt)
s = '2016/1/22 5:32:44'
fmt = '%Y/%m/%d %H:%M:%S'
datetime.datetime.strptime(s, fmt)
s = 'January 23, 2019 5:22 PM'
fmt = '%B %d, %Y %H:%M %p'
datetime.datetime.strptime(s, fmt)
s = 'On January the 23rd 2019 at 5:22 PM'
fmt = 'On %B the %drd %Y at %H:%M %p'
datetime.datetime.strptime(s, fmt)<jupyter_output><empty_output><jupyter_text>Converting datetimes to stringThe **strftime** method converts a date, time, or datetime to a string. It stands for **string format time**. Begin with a date, time, or datetime and use a string with directives to make the conversion.<jupyter_code># Convert directly into a string of your choice. Lookup directives online
my_date.strftime("%Y-%m-%d")
# Another more involved directive
my_date.strftime("Remembering back to %A, %B %d, %Y.... What a fantastic day that was.")<jupyter_output><empty_output><jupyter_text>Date and Datetime additionIt's possible to add an amount of time to a date or datetime object using the timedelta function. timedelta simply produces some amount of time measured in days, seconds and microseconds. You can then use this object to add to date or datetime objects.**`timedelta`** objects are constructed with the following definition: **`timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)`**<jupyter_code>my_timedelta = datetime.timedelta(seconds=5000) 
my_timedelta
type(my_timedelta)
# add to datetime
my_datetime + my_timedelta
# original
my_datetime
# add to date
my_date + my_timedelta
# original date. Nothing changed since 5000 seconds wasn't long enough to make an extra day
my_date
# now there is a change
my_date + datetime.timedelta(days = 5)
# add weeks
a = my_datetime + datetime.timedelta(weeks=72, days=4, hours=44)
# the difference between the underlying string representation and the print function
print(a.__repr__())
print(a)
datetime.timedelta(weeks=72, days=4, hours=44)<jupyter_output><empty_output><jupyter_text>Third-Party library `dateutil`For improved datetime handling, you can use [dateutil][1], a more advanced third-party library. Pandas actually uses this library to for its complex date handling. Two of it's most useful features are string parsing and datetime addition. Advanced string handlingThe `parse` function handles a wide variety of strings. It returns the same datetime type from above. See [many more examples][2] in the documentation.[1]: https://dateutil.readthedocs.io/en/stable/[2]: https://dateutil.readthedocs.io/en/stable/examples.htmlparse-examples<jupyter_code>from dateutil.parser import parse
parse('Jan 3, 2003 and 5:22')<jupyter_output><empty_output><jupyter_text>Pandas uses this under the hood.<jupyter_code>import pandas as pd
pd.Timestamp('Jan 3, 2003 and 5:22')<jupyter_output><empty_output><jupyter_text>Advanced datetime additionAn upgrade to the **`timedelta`** class exists with the **`relativedelta`** class. Check [this stackoverflow][1] post for more detail or see the [documentation for examples][2].[1]: http://stackoverflow.com/questions/12433233/what-is-the-difference-between-datetime-timedelta-and-dateutil-relativedelta[2]: https://dateutil.readthedocs.io/en/stable/relativedelta.htmlexamples<jupyter_code>from dateutil.relativedelta import relativedelta<jupyter_output><empty_output><jupyter_text>There are two ways to use it. First, you can pass it two datetimes to find the difference between the two.<jupyter_code>dt1 = datetime.datetime(2016, 1, 20, 5, 33)
dt2 = datetime.datetime(2018, 3, 20, 6, 22)
relativedelta(dt1, dt2)<jupyter_output><empty_output><jupyter_text>Second, create an amount of time with the parameters years, months, weeks, days, etc... and then add that to a datetime.<jupyter_code>rd = relativedelta(months=3)
dt1 + rd<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09556239015817224, 'fraction_numerical': 0.026471880492091388, 'mean_word_length': 6.186266771902131, 'pattern_counts': {'":': 0, '<': 81, '<?xml version=': 0, '>': 81, 'https://': 8, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '2898', 'license': 'MIT', 'n_tokens_mistral': 2939, 'n_tokens_neox': 2694, 'n_words': 1003, 'path': 'jupyter_notebooks/pandas/mastering_data_analysis/07. Time Series/06. Python datetime module.ipynb', 'repo_name': 'manual123/Nacho-Jupyter-Notebooks', 'size': '9104'}