A Deep Dive Into Date And Time In Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
working with date and time data can be really challenging with all the different date and time formats ISO standards different time zones Daylight Saving adjusting for time traveling with technium particles it goes on and on today I want to take you through how Python's built-in daytime package Works talk about some of the Alternatives that are out there to help you make dealing with dates and times easier and whether those alternatives are actually necessary learning about these things help you become a better software engineer and hone your critical thinking skills if you want to take this step further I have a free workshop for you that teaches you how to diagnose existing code and quickly see what the main problems are it's one of the most important things to get good at especially as you start moving into a more senior position you can get access to the workshop by going to ion.com diagnosis the workshop is organized around three factors and contains loads of code examples also from well-known python packages just grab it for free at iron dot gold slash diagnosis the link is also in description why is dealing with dates and times such a pain it's a dichotomy between on the one hand computer software which tends to be ordered and structured and generic and on the other hand the quite unstructured way would deal with dates and times things are never the same some years don't have the same number of days because they are leap year months don't have the same number of days each day doesn't have the same number of hours if you consider daylight time saving not all countries have daylight time saving and those that do May apply daylight time saving at a different moment in time then we have time zones which are not divided by longitudinal geodesics due to political and historical reasons in short it's a big mess in our little computer bubble we do have some kind of standard way of representing dates and time most computer systems count time starting from an arbitrary point in time called the Unix ebook January 1st 1970 at zero zero zero hours UTC watch UTC I'll talk more about that in a minute so you next time is measured in seconds since January 1st 1970. you can easily get the Unix timestamp in Python with just a few lines of code so I've imported the time package here and you can simply print time dot time and this is going to give you the Unix timestamp which looks like this so these are the seconds that have passed and this is the fraction of the second that has passed so far so it's a floating point value now because this is a floating Point python can't guarantee anything about the Precision if you want a more precise representation you can also get the time underscore NS which stands for nanoseconds and if we print that then we're going to get an actual integer number that represents the number of nanoseconds passed since January 1st 1970. an interesting thing about Unix time is that since most older operating systems are 32-bit they store the Unix time in a 32-bit signed integer you probably already know where this is going if you're aware of the Year 2K problem but there's also a year 2038 problem which is when the signed 32-bit integer runs out of values in this older operating system specifically at 3 14 am and 7 seconds on January 19 2038 the 32-bit integer is going to overflow resulting in the year 2038 problem now python itself won't have a direct issue with it because integers don't have a fixed number of bits in Python it's Dynamic but python of course under the hood uses OS functions to get the current time so they're still going to be a problem due to that in short if you want to avoid catastrophic consequences to your critical systems in 2038 make sure that in the next 15 years or so you switch to a 64-bit operating system or more if you're planning to still run a critical system on a 32-bit OS in 2038 can you just please fire yourself the world thanks you like I mentioned before your next time is expressed in the UTC time zone UTC stands for universal time coordinated or coordinated universal time before 1972 this time was called Greenwich mean time GMT sometimes erroneously calls granite's Meridian time and it's pronounced Greenwich not Greenwich unless you live in the Land of Oz UTC is a Coordinated Time scale maintained by The Bureau International it's not adjusted for daylight saving time so there's always 24 hours in a day it's also known as z-time or Zulu time which sounds way cooler than UTC right let's take a look at how we deal with dates and times in Python I've imported the daytime class from the date time package I think by the way it was a bad decision to use date time lowercase as the class name here because it mixes up the package name and the class name which is really annoying because if you do import date time then you have to write date time dot date time everywhere you can use an Elias but I think it's better to just let the class name start with an uppercase letter so that you can easily distinguish between the backer's name and the class name anyway daytime class it's very easy to use you can create a variable let's call that some date and let's go to the date time and then we can basically specify the date in terms of let's say the year and we're going to put some kind of random dates and let's say it's going to be 6 AM and now we've created a date and I can print this date as well and if we run this then this is what we're going to get since python 3.6 daytime also supports ISO 8601 parsing which is a standard way of representing dates and times as a string instead of calling the initializer here I can call the from ISO format method that's going to return a date time object and I can pass it on ISO string like for example 2022.09 16 and the time is going to be I don't know 1405 and let's say 13 milliseconds it doesn't really matter and when I run this we still get a regular date object just as usual but now we've read it from an ISO string getting the current date is also really easy because daytime has a no method and when we run this we're going to get the current date so as you can see I'm recording this video on September 16. comparing dates is also really easy we can simply use the comparison operators foreign this is going to print false date and time objects can be broadly divided into two categories aware and naive if an object contains time zone information its time zone aware else it's called time zone naive in Python objects like daytime have an optional property tzat info that contains the time zone information by default date time is time zone naive so this object isn't set to anything if you want times on aware Day times you need a module that can deal with all the issues related to time zones that I mentioned earlier in Python we have the bytz package for this it's not built into python you have to add it as a dependency you might wonder where all this time zone and daylight savings settings come from well basically most software in the world retrieves that information from a centralized time zone database which is currently maintained by one guy in California well kinda it's a fascinating story I don't have time to dive into it in this video but there's a link in description to an article on medium if you want to read more about it let's look at a few time zone examples so in order to work with time zone I'm going to use the PYT set package you need to install this especially it's not bundled with python so from PYT Z I'm going to import time zone that's going to help us deal with time zones so if we start with the sumdate variable let me just delete this code you can now add time zone support to it so default as I've mentioned date time is time zone naive it doesn't know anything about time zones we have to explicitly deal with it what we can do is create the time zone function here to create a time zone info object so let's start simple by having a UTC time zone like so and now we can localize the dates to that time zone so the time zone info object has a localized method that gets a date time object so that's some date and then we can print the localized time and let me also print some dates before that like so and let me run this code and then this is what you're going to see so now actually when you print the date there is time zone information included in because it's no longer time zone naive now that it has time zone information we can convert between different time zones so for example I can create a certain time zone like so and then I can print this localized date this time zone where date as time zone Sydney so when I convert this UTC time into the time in Sydney we're going to get five minutes past midnight similarly I can create another time zone let's say we have Amsterdam and when we run that it means that in Amsterdam is two hours later than the UTC time the built-in daytime package in Python is nice but it has some limitations first there are lots of different modules and types date time date time calendar date util t-shirt info time Delta and more it gets confusing pretty quickly if you need to do more advanced things with dates and times times on conversion with daytime is not bad but you need to create a diesel info object explicitly to convert daytime into another time zone and by default daytime is times on naive it doesn't take time zones into account unless you explicitly indicate that it should now over the past few years a lot of things have been improved in the daytime package like adding support for parsing ISO 8601 strings but then there's still some functionalities missing such as humanizing dates and durations people have developed alternative packages that deal with dates and times such Arrow DeLorean and pendulum these packages generally offer a nicer interface than the standard date time package I won't go into detail for each of these packages since they all mostly try to solve the same limitations but I am going to take a closer look at pendulum today pendulum provides a drop-in replacement for the daytime class but adds simpler time zone handling Day times are times on aware by default and it has a bunch of extra features such as localization or being able to easily write a human readable version of times one let's take a look at how pendulum works but before I do that I'd really appreciate if you would take the time to hit the like button if you are enjoying this video so far it's going to help YouTube recommend my content to others I want to show you the basics of how you use pendulum so the first step is that we're going to import the pendulum package and of course you need to install a package the main difference between pendulum and daytime is that pendulum is by default time zone aware so instead of creating a daytime like this what I can do now is pendulum dot daytime and then we're going to pass it a date similar to what we did to daytime so just something like this so we have the date and the time and then I can also indicate the time zone so I'm now indicating UTC but this is actually the default time zone if you create a pendulum date time so there we go so the daytime package is no longer needed the pendulum gives us a subclass of daytime but if I run this then we're going to get this time and there is also the time zone information in there now time zone conversions are also really simple for example you can simply write some date Dot in time zone and then we Supply the time zone and then this is going to be the equivalent time in Australia Sydney pendulum also handles time transitions properly so if you are just on the edge of reaching summer time or winter time pendulum is going to take care of this so here I've put in a date I think this is actually from opinion documentation in the Europe or Paris time zone so print the data and then I add a microseconds and then I subtract it again so when I run this you see that it's actually exactly on a switch between Daylight Saving Times because from 159.59 I add one microseconds and I'm going to 3 AM and back to 159.59 so pendulum takes care of these kinds of transitions for you automatically another nice thing is that pendulum provides localization so I can write pendulum dot set local and then I'm going to set no which is the Dutch Locale and then I can print let's say some dates format and now I can print a formatter today so what I want to do is the day of the week and the day and the month and the years and then when I print it like this then we're going to get a Dutch localized version of the date because I set the lookout so Dutch and I can change the lookout to something else let's say you want to print it in Italian and then we're going to get the date printed in Italian which is really simple and really useful now you can override the lookout so default logos no Italian but if you want to override it two let's say German then we can simply pass it as an argument to the format method and then we're going to get a German date there are some standard localized format so instead of having to write this long string here actually this should have been four y's and not five you can also write something shorter for example this is going to print only the time and that looks like this in German but if I change to let's say en then it's going to look slightly differently because that uses the am BM style there's a couple of different options here this is another example of a localized format and that looks like this so that prints the day of the week and the actual date and the time as well and then of course if I change the local it's also going to print it in the correct lookup you also see that it's different because in English who writes the day after the month and in Dutch we write it in front of the month another thing you can do is print a time span and also print it in a humanized way so that we puny humans also understand it so let's say I can print pendulum dots now and then I'm going to add one year and I'm going to print diff for humans and then this is what we're going to get we get an error because it should be here it should be years let's try that again and then there we go and it's still in Italian maybe I should put it back to some other local because I don't understand any Italian so here it is in Dutch in one year that's what it means and also here you can override the local again so I can change this back to let's say English and then we're going to get an English version of this time span So currently the time span is printed as a relative string something is going to happen in one year you can also simply have an absolute time span like three days or one year if you want that you simply pass the absolute argument and you set it to true and this is what we're going to get one year absolute value there are also a couple of helpful properties for example there is let me print pendulum not now then we have for example the day of the year so if you print the day of the year we're going to have 259 so it's the 259th day of the year when I'm recording this there's a couple of others like uh day of week so I'm recording this on a Friday so that's the fifth day of the week There's also week of month and week of year for example here week of year which is I think week 37 yeah so it's week 37 and a few others like you can get the uh in timestamp for example like like so just using a simple property and there's also a float version of this which prints the float and then also adds the Precision like we've seen in the basic daytime example I showed earlier next to that there's also a bunch of other helpful methods for example if you want to know the start of today you can get that very easily I just write pennile.now Dot start off day and now we're going to get the time representing the start of the day in the current time zone which is I'm at UTC plus two normally it's plus one but it's daylight saving so it's plus two and you also have end of the aim which gives us the time at the end of the day and that looks like this another thing that's not possible in the built-in daytime module but that is possible with pendulum is that durations also support years and months so we can write something like this pendulum dot duration and then I can specify a number of years and months like so and then I can simply print duration.days and I'm going to get the total number of days that the duration represents which is 1185 in this example so you see lots of things are possible especially like the localization option that pendulum provides localization by the way is a topic all in itself I really like to do a more in-depth video about it now I did do a dashboard application tutorial a couple of weeks ago I put a link to that video series to the top you can watch the first part and there I also touch on localization a little bit so should everyone switch to a package like pendulum well it's nice it adds very useful extra features but here are a couple of things to think about first pendulum hasn't seen a new release for a while last version on GitHub was published over two years ago this is always a risk with using external package and production code you have to consider whether they're being actively maintained and for how long second the built-in daytime package is being worked on as well there are only minor changes in that package in Python 3.11 like a slightly more robust from ISO format method but as more functionality is added you might not need that external package anymore and then you potentially have to do a lot of refactoring work to move away from the package you used before though pendulum does inherit directly from the daytime class which reduces that risk somewhat and finally do you really need the extra features if you don't simply stick with the built-in daytime package it's not perfect but it's pretty good I hope this video gave you some food for thought about dealing with dates and times in your own code next to daytime python has lots of other interesting packages for example bath flip if you want to learn more about dealing with Buffs check out this video thanks for watching take care and see you next week
Info
Channel: ArjanCodes
Views: 41,035
Rating: undefined out of 5
Keywords: python date and time, python date time, datetime python, python dates, date and time python, datetime function, datetime, python datetime package, datetime package, pendulum datetimes, pendulum datetime, python datetime, python programming, python programming tutorial, python tutorial, utc time zone explained, utc time, date time, issues with date and time, dates python, pendulum, pendulum dates, datetimeindex python, utc time zone, pendulum tips, utc time means
Id: TFa38ONq5PY
Channel Id: undefined
Length: 19min 39sec (1179 seconds)
Published: Fri Oct 14 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.