Learn Python Series (#22) - Handling Dates and Time Part 2

in #utopian-io7 years ago (edited)

Learn Python Series (#22) - Handling Dates and Time Part 2

<p dir="auto"><img src="https://images.hive.blog/768x0/https://cdn.utopian.io/posts/8a0310028ae19f4bd173260aa46289f328bcpython_logo.png" alt="python_logo.png" srcset="https://images.hive.blog/768x0/https://cdn.utopian.io/posts/8a0310028ae19f4bd173260aa46289f328bcpython_logo.png 1x, https://images.hive.blog/1536x0/https://cdn.utopian.io/posts/8a0310028ae19f4bd173260aa46289f328bcpython_logo.png 2x" /> <p dir="auto"><strong>Full additional iPython tutorial sample code file included here:<br /> <a href="https://github.com/realScipio/learn-python-series/blob/master/datetime-02.ipynb" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">https://github.com/realScipio/learn-python-series/blob/master/datetime-02.ipynb <h4>What Will I Learn? <ul> <li>You will learn about the <code>datetime module and its most-used classes and their methods; <li>about date/time arithmetic using <code>timedelta's, which is really interesting and fun for me at least! <li>about the methods <code>timetuple() and <code>strftime() & <code>strptime()forming a "conversion bridge" between <code>time and <code>datetime instances; <li>and most importantly, by going over all methods and techniques discussed in Parts 1 & 2 of the <code>Handling Dates and Time subseries, hopefully you're able to know the answer - for yourself - what are the differences between the <code>time and <code>datetime modules, and when to use which. <h4>Requirements <ul> <li>A working modern computer running macOS, Windows or Ubuntu; <li>An installed Python 3(.6) distribution, such as (for example) the Anaconda Distribution; <li>The ambition to learn Python programming; <h4>Difficulty <p dir="auto">Intermediate <h4>Curriculum (of the <code>Learn Python Series): <ul> <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-intro" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series - Intro <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-2-handling-strings-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#2) - Handling Strings Part 1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-3-handling-strings-part-2" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#3) - Handling Strings Part 2 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-4-round-up-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#4) - Round-Up #1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-5-handling-lists-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#5) - Handling Lists Part 1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-6-handling-lists-part-2" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#6) - Handling Lists Part 2 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-7-handling-dictionaries" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#7) - Handling Dictionaries <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-8-handling-tuples" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#8) - Handling Tuples <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-9-using-import" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#9) - Using Import <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-10-matplotlib-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#10) - Matplotlib Part 1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-11-numpy-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#11) - NumPy Part 1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-12-handling-files" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#12) - Handling Files <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-13-mini-project-developing-a-web-crawler-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#13) - Mini Project - Developing a Web Crawler Part 1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-14-mini-project-developing-a-web-crawler-part-2" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#14) - Mini Project - Developing a Web Crawler Part 2 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-15-handling-json" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#15) - Handling JSON <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-16-mini-project-developing-a-web-crawler-part-3" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#16) - Mini Project - Developing a Web Crawler Part 3 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-17-roundup-2-combining-and-analyzing-any-to-any-multi-currency-historical-data" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#17) - Roundup #2 - Combining and analyzing any-to-any multi-currency historical data <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-18-pymongo-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#18) - PyMongo Part 1 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-19-pymongo-part-2" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#19) - PyMongo Part 2 <li><a href="https://steemit.com/utopian-io/@scipio/learn-python-series-20-pymongo-part-3" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#20) - PyMongo Part 3 <li><a href="https://utopian.io/utopian-io/@scipio/learn-python-series-21-handling-dates-and-time-part-1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Learn Python Series (#21) - Handling Dates and Time Part 1 <h1>Learn Python Series (#22) - Handling Dates and Time Part 2 <p dir="auto">In the previous tutorial of the <code>Learn Python Series regarding the handling of dates and time (part 1) we already learned that both the <code>time module as well as the <code>datetime module provide functionality for handling dates and times. The <code>time module has some more focus on support for UNIX timestamps, and in this episode (part 2) we're going to discuss in which specific areas the <code>datetime modules shines. <p dir="auto">Let's begin! <h1>The <code>datetime module <p dir="auto">As compared to the <code>time module, the <code>datetime module - instead of mostly working with 9-tuples / time_structs and timestamps / epoch integers (ticks) - has a more modular / object-oriented type of interfacing. I will talk about the following classes, which are included in the <code>datetime module: <ul> <li><code>datetime.time: representing time, independent of its date; <li><code>datetime.date: representing dates only, independent of time; <li><code>datetime.datetime: for a combination of date & time on some date; <li><code>datetime.timedelta: for dealing with differences of 2 date objects or 2 time objects. <h1>The <code>datetime.time class <pre><code>import datetime t1 = datetime.time(20, 1, 59, 123456) print(t1) <pre><code>20:01:59.123456 <p dir="auto">The variable <code>t1 is now a <code>datetime.time instance, which has <strong>attributes. These are: <pre><code>hour = t1.hour minute = t1.minute second = t1.second microsecond = t1.microsecond timezone_info = t1.tzinfo print('Hour: ', hour) print('Minute: ', minute) print('Second: ', second) print('Microsecond: ', microsecond) print('Timezone info: ', timezone_info) <pre><code>Hour: 20 Minute: 1 Second: 59 Microsecond: 123456 Timezone info: None <h1>The <code>datetime.date class <p dir="auto">In order to create a <code>date instance, just pass in 3 values (year, month, day) as the arguments for <code>datetime.date(). <pre><code>d1 = datetime.date(2012, 12, 31) print(d1) <pre><code>2012-12-31 <p dir="auto">Variable <code>d1 is now a <code>datetime.date instance, which has (defaault) attributes as well, being: <pre><code>year = d1.year month = d1.month day = d1.day print('Year: ', year) print('Month: ', month) print('Day: ', day) <pre><code>Year: 2012 Month: 12 Day: 31 <h3><code>datetime.date.today() method <p dir="auto">If you want to create a current day <code>date instance, use the <code>datetime.date.today() class method: <pre><code>today = datetime.date.today() print(today) <pre><code>2018-05-02 <h3><code>datetime.date.timetuple() method <p dir="auto">You can still use 9-tuples / timestructs on <code>datetime.date instances by calling the <code>datetime.date.timetuple() method. The exact same 9-tuple / time_struct attributes, as I've explained in <code>Handling Dates and Time Part 1 regarding the <code>time module are available for the <code>datetime module as well via the <code>datetime.date.timetuple() method, like so: <pre><code>today_tt = today.timetuple() year = today_tt.tm_year month = today_tt.tm_mon month_day = today_tt.tm_mday hour = today_tt.tm_hour minute = today_tt.tm_min second = today_tt.tm_sec week_day = today_tt.tm_wday year_day = today_tt.tm_yday daylight_savings = today_tt.tm_isdst print('Year: ', year) print('Month: ', month) print('Day of Month: ', month_day) print('Hour: ', hour) print('Minute: ', minute) print('Second: ', second) print('Day of Week: ', week_day) print('Day of Year: ', year_day) print('Daylight savings: ', daylight_savings) <pre><code>Year: 2018 Month: 5 Day of Month: 2 Hour: 0 Minute: 0 Second: 0 Day of Week: 2 Day of Year: 122 Daylight savings: -1 <h3><code>datetime.date.ctime() method <p dir="auto">There's also a <code>ctime() method, like in the <code>time module, returning a date/time string representation. But because the <code>datetime.date class doesn't deal with time, the time components returned are that of midnight: <pre><code>today_ctime = today.ctime() print(today_ctime) <pre><code>Wed May 2 00:00:00 2018 <h3><code>datetime.date.replace() method <p dir="auto">A convenient way to create new <code>date instances by using an existing <code>date instance as a starting point, is the <code>replace() method: <pre><code>today = datetime.date.today() print('Today: ', today.ctime()) a_month_from_today = today.replace(month=6) print('A month from today: ', a_month_from_today.ctime()) a_year_from_today = today.replace(year=2019) print('A year from today: ', a_year_from_today.ctime()) <pre><code>Today: Wed May 2 00:00:00 2018 A month from today: Sat Jun 2 00:00:00 2018 A year from today: Thu May 2 00:00:00 2019 <h1>The <code>datetime.datetime class <p dir="auto">You probably guessed it: the <code>datetime.datetime class is best used when you're dealing with date/time values in which relevant values for both date and time are present. <h3><code>datetime.datetime.now() / <code>datetime.datetime.today() <p dir="auto">Works the same as the <code>datetime.date.today() method, but now includes a time component as well: <pre><code>now = datetime.datetime.today() print(now) <pre><code>2018-05-02 21:40:46.430434 <h3><code>datetime.datetime.combine() <p dir="auto">Another pretty handy method is <code>combine(): it creates a <code>datetime instance by combining one <code>date instance plus 1 <code>time instance, like so: <pre><code>some_date = datetime.date(2015, 9, 14) some_time = datetime.time(14, 53, 0) combined_datetime = datetime.datetime.combine(some_date, some_time) print('some_date: ', some_date) print('some_time: ', some_time) print('combined_datetime: ', combined_datetime) <pre><code>some_date: 2015-09-14 some_time: 14:53:00 combined_datetime: 2015-09-14 14:53:00 <h1>The <code>datetime.timedelta class <p dir="auto">A really nice class - at least I think it's cool! - is the <code>datetime.timedelta class. It's possible to execute basic arithmetic on date / datetime instances, for example calculate how many dats are in between two dates, by subtracting them: <pre><code>today = datetime.date.today() some_day = datetime.date(2012, 10, 10) diff_days = today - some_day print(diff_days) <pre><code>2030 days, 0:00:00 <p dir="auto">By subtracting two dates, you (implicitly) create a <code>timedelta instance. <pre><code>print(type(diff_days)) <pre><code><class 'datetime.timedelta'> <p dir="auto">And you can use a <code>timedelta to do arithmetic to produce another date! <p dir="auto">You can create timedeltas, in multiple time units, yourself, like so: <pre><code>one_week = datetime.timedelta(weeks=1) one_day = datetime.timedelta(days=1) one_hour = datetime.timedelta(hours=1) one_minute = datetime.timedelta(minutes=1) one_second = datetime.timedelta(seconds=1) one_millisecond = datetime.timedelta(milliseconds=1) one_microsecond = datetime.timedelta(microseconds=1) print('one_week: ', one_week) print('one_day: ', one_day) print('one_hour: ', one_hour) print('one_minute: ', one_minute) print('one_second: ', one_second) print('one_millisecond: ', one_millisecond) print('one_microsecond: ', one_microsecond) <pre><code>one_week: 7 days, 0:00:00 one_day: 1 day, 0:00:00 one_hour: 1:00:00 one_minute: 0:01:00 one_second: 0:00:01 one_millisecond: 0:00:00.001000 one_microsecond: 0:00:00.000001 <h3>Performing date arithmetic using timedeltas <p dir="auto">Now the fun part begins, by combining date / time / datetime instances with timedeltas and regular math operators! <pre><code>today = datetime.date.today() print('Today: ', today) one_week = datetime.timedelta(weeks=1) last_week = today - one_week print('Last week: ', last_week) next_week = today + one_week print('Next week: ', next_week) print('Days in between next and last week: ', next_week - last_week) <pre><code>Today: 2018-05-02 Last week: 2018-04-25 Next week: 2018-05-09 Days in between next and last week: 14 days, 0:00:00 <p dir="auto">Because <code>timedelta objects can work with floats, integers, and other <code>timedelta objects, you can create interesting combinations. <p dir="auto">How about this for getting creative with <code>timedelta arithmetic? <pre><code>vp_recharge_period = datetime.timedelta(days=1) * 0.1 powerdown_period = datetime.timedelta(weeks=13) num_votes_during_powerdown = powerdown_period / vp_recharge_period print('vp_recharge_period: ', vp_recharge_period) print('powerdown_period: ', powerdown_period) print('num_votes_during_powerdown: ', num_votes_during_powerdown) <pre><code>vp_recharge_period: 2:24:00 powerdown_period: 91 days, 0:00:00 num_votes_during_powerdown: 910.0 <h1><code>datetime object string formatting & parsing <p dir="auto">In the previous tutorial, regarding the <code>time module, we've in-depth covered the usage of <code>time.strftime() (for string formatting) and <code>time.strptime() (for date/time string parsing). The same type of methods are also available on the <code>datetime class. <p dir="auto">For those that haven't read the previous tutorial regarding <code>time.strftime() and <code>time.strptime(), I'll briefly demonstrate how to use the same methods in a <code>date.strftime() and <code>date.strptime() context. <p dir="auto">We define a date/time format string, create a datetime object (<code>now) and convert between the two, proving the same <code>now is used for variables <code>s (string) and <code>p (parsed). <pre><code>format_string = "%A, %d %b %Y (%H:%M:%S)" now = datetime.datetime.today() s = now.strftime(format_string) p = datetime.datetime.strptime(s, format_string) print('strftime:', s) print('strptime:', p) <pre><code>strftime: Wednesday, 02 May 2018 (23:32:58) strptime: 2018-05-02 23:32:58 <p dir="auto"><strong>Nota bene: Since we've also covered the <code>datetime.date.timetuple() method, I'm sure you'll be able to conveniently make use of the most handy methods available on both the <code>time and <code>datetime classes, while at the same time being able to convert between the two. <h1>PS: A word or two about the <code>datetime.tzinfo class <p dir="auto">The <code>datetime module is able to work with time zones as well, but as subclasses of the <code>datetime.tzinfo class, which is abstract, and therefore you need to provide your own implementations to make the methods work. It can be ... "tricky", to say the least. You could also say that working with timezones via the <code>datetime module is oftentimes considered "a nightmare" by many Pythonistas. <p dir="auto">But no worries! The next <code>Learn Python Series episode is about the external date/time package <code>Maya, which makes your life a whole lot easier, including handling timezones. <h1>What did we learn, hopefully? <p dir="auto">In this episode, we went over the "ins-and-outs" of the <code>datetime module and its classes and methods. Some of the methods are pretty straightforward (such as <code>combine() and <code>replace()) yet powerful to use. The most "fun" part - at least I think so - about the <code>datetime module, is the <code>datetime.timedelta class. Because it allows you to do date/time arithmetic using floats, integers and other timedeltas, you can get pretty creative with it in just a few lines of code! <p dir="auto"><strong>Nota bene: One of the <strong>core take-aways I wanted to address here, by first going over in-depth regarding the <code>time module, and then doing the same for the <code>datetime module, is that although they overlap to a certain extent - which became clear, hopefully, by me discussing al those methods - is that both modules have their specific strengths. And, because of the <code>timetuple() method and the <code>strftime() & <code>strptime() methods, forming a "conversion bridge" between the <code>time module and the <code>datetime module, you can freely choose to combine whatever you want! <h3>Thank you for your time!
Sort:  

Hey @scipio

We're already looking forward to your next contribution!

Decentralised Rewards

Share your expertise and knowledge by rating contributions made by others on Utopian.io to help us reward the best contributions together.

Utopian Witness!

Vote for Utopian Witness! We are made of developers, system administrators, entrepreneurs, artists, content creators, thinkers. We embrace every nationality, mindset and belief.

Want to chat? Join us on Discord https://discord.me/utopian-io

Thank you @utopian-io! Bleep! Bleep!

Thank you for the contribution It has been approved.



Chat with us on Discord.Need help? Write a ticket on https://support.utopian.io.

[utopian-moderator]

Thank you too! :-)

this is very valuable info in your posts. It makes me wish i was less busy to learn python script.

Thanks for the kind words

Hey this is great! Do you mind if I link to this tutorial from my own? I will be adding it to utopian.io soon and I'd like to include it as a refrence link at the bottom for those who don't understand the date and time manipulations my code uses. I'd like to link to a few others in this series as well such as handling strings and lists and using import. Let me know. Are you on discord?

Feel free to link to any of my Learn Python Series episodes!

The explanation of the differences really helped me understand them a bit better.

I was actually coding not too long ago and ran into issues trying to parse dates and times. This helped a ton.

Good! :-)

Toda I learned about the methods timetuple() and strftime() & strptime()forming a "conversion bridge" between time and datetime instances. Thanks to you for the valuable post.

Did you seriously copy-paste that line from my tutorial, just to post this comment???

I really love your post.

My post loves you too!


Thank you so much for posting so beautiful.
SIR was very good for your posting. Because you get many benefits with the right information, so thank you very much for posting so beautiful and helping others by providing such information in the future.Dear @scipio,