hi there serdar yagerlop here for infoworld in this episode of smart python we're going to take
a look at how time and date values are handled in python times and dates are real world things
meaning they're messy they're inconsistent and they're sometimes hard to work with python has
a whole separate data type devoted to working with dates and times called appropriately enough
date time and it resides in a standard library module called also appropriately enough date time
now one of the things that datetime the data type tries to do is help you get a handle on all of
the messiness and inconsistency that comes with working with dates and times by converting dates
and times into objects so let's start by looking at the basic way that we obtain and work with
dates and times in this first script here i'm going to start by importing the date time type
from the date time library the data type is the actual class that represents dates and times
the library is where it lives along with a number of other important tools but for now i'm going to
concentrate on the date time type itself one of the most common things we do with date time
is obtain the current date and time and we do that by using the date times now method
this will use whatever the operating system offers to provide the current date and time and
we'll translate that information into a date time object this way no matter what platform you're on
you're going to get consistent and usable results so if we print the resulting date time object
we'll see a year a month a day and the hour minute second and microsecond all as part of the default
string representation for that object but we can also deal with each of these elements individually
and they're just properties of the object as you can see from these other print statements
where we're taking them all out and printing them in succession and we can also get a date
time object and get from a representation of the time as a unix timestamp this is a floating point
number that represents the number of seconds since january 1st 1970. this is commonly used
in many applications and it's nice to know that we have it available by way of a common method we
don't have to pass anything else to it we don't have to use any other libraries to extract it
now normally date time objects do not have any time zone information associated with them they
are naive as the term goes and this last print statement we have here attempts to show that
the name of the time zone for the date time object and any actual data about it both show up as none
so that means this date time has no time zone data associated with it now a naive date time is
okay if you're just using it to say mark the time between when you start and stop doing the process
but if you're recording a daytime object for later reference like in a database
you want to have some kind of time zone information associated with it otherwise
it can become very confusing what exact time and date you're actually talking about
the easiest way to do this and often the most immediately useful is just to generate
a daytime object using the utc time zone this way there's no ambiguity about it you can always
convert other time zones non-destructively i'll show you how to do that in just a little bit
so in the second script we're doing exactly what we did in the first one we're just
using a different method utc now to get a date time object with a utc time zone baked into it
you'll notice that when we do this the actual time that we get is a little different utc is
a four hours difference from the eastern time zone which is where i'm currently residing now to work
in greater detail with time zones python 3.9 and up provide you with some powerful new libraries
to do this one of them is the zone info library which obtains time zone conversion information
from a local database in a standard format so that you can use it to make adjustments for local
times based on place names the other is a library called tz data this supplies the actual timezone
database information itself see some operating systems have that time zone information built in
but others don't and so you need something like tz data to fill that gap microsoft windows for
instance does not have that time zone information built in so i've used as you can see here pip
install to add tz data to this instance of python so that we can get that information now in this
example i'm obtaining data about two different time zones from zone info the first is the time
zone for new york city which i obtained by way of using this specific string so if you look online
for instance at nodatime.org you can find the exact strings that you would need to provide
for specific locales they're part of a standard so it shouldn't be too difficult to look them up
once we have the time zone data for new york we can then pass that to datetime.now as a parameter
the parameter t z to indicate we want to use that time zone to construct that datetime object
you'll notice now that we have in the output to the program an actual time zone name and locale
you'll also notice that the string representation of the time is a little bit different it has that
minus 4 at the end which indicates an adjustment made from utc time the second time zone that we've
obtained for los angeles we can use to construct a new date time object from the old one using the
as time zone method this gives us a copy of the original date time object but with its time zone
adjusted for los angeles so all of the complexity of figuring out things like daylight savings time
assuming we ever have to deal with that again those are all abstracted away with this process
very common operation with daytime objects is finding differences between two dates
or two times if you subtract two dates from each other you don't get another date object
instead you get a new kind of object called a time delta a time delta isn't itself a date or
a time instead it's a representation of a total difference between two times so in this example
we'll first create a date time object manually and this we do by passing
gear month day hour minute second all as integers into the date time object we then create a time
delta object one day earlier as we call it by just using days equals one as the perimeter notice that
we're using a negative value for the days minus 1. this indicates that we want to go back in time
so all we need to do is take this time delta and combine it with the date time value
to get the new date time that we want and as you can see from the output instead of may 12 2020 we
now have may 11 2020. and note that we can add or subtract as needed see if we wanted to we could
get the same results by creating a di by creating a time delta with a day's value of positive one
and then subtracting that from our date time object so you have a lot of flexibility in terms
of how you can combine date times and time deltas to get the answers you need so to sum up daytime
objects in python let us work with dates and times as rich objects rather than as raw unix timestamps
or mere integers we can associate them with specific time zones or with no time zone at all if
we want to live dangerously and we can apply time zone adjustments to existing date time objects
non-destructively we can also use time delta objects to measure or generate differences
between two date time objects the better to do things like store intervals efficiently
so that's it for this video if you liked it please leave a comment below don't forget
to subscribe to the tech talk channel on youtube and for more smart python
and more david serdar be sure to follow me on facebook youtube and infoworld.com