Python Tutorial: Datetime Module - How to work with Dates, Times, Timedeltas, and Timezones
By Corey Schafer
Summary
Topics Covered
- Naive Datetimes Lack Timezone Data
- Timedeltas Enable Date Arithmetic
- Datetimes Combine Date and Time
- Prefer Pytz Over Standard Timezones
- Localize Naive Before Astimezone
Full Transcript
hey everybody how's it going in this video we'll be learning how to work with dates within python now it's extremely important to know how to work with dates because you're going to be using these in just about every type of application
that you're going to write and dates can sometimes be overwhelming because there's so much to think about so for example in Python we have dates times date times time zones time deltas and
it's not really obvious when we should use what so let's go ahead and dive in and look at some examples of this to get more comfortable so the main module for working with dates in Python is the date
time module and we can import that just by saying import date time now the first thing to talk about when working with dates and times is understanding the difference between naive and aware date
times and you'll hear these two terms a lot now naive dates and times don't have enough information to determine things like time zone or daylight savings times but they're easier to work with if you
don't need that level of detail but if you do need that level of detail to avoid confusion then you need to use aware dates and times now these do have enough information to determine their
time zone and keep track of daylight savings time now since naive date times are the easiest to work with we'll start off by looking at those first so first
let's look at date time. dat so with a normal date we're going to be working with a year month and day now there are a couple of different ways that we can
create a date but to create a date right now I'm just going to do a date time.
dat and I'm going to pass in a year a month and a day so now let's go ahead and print this out so we can see what this looks like so you can see that when
we printed that out that it gave us a date of 2016 0724 now when you're creating these dates be sure to just pass in regular
integers as the days and months with no leading zero because if we were to pass in 07 here and run that you can you see that this gave us a syntax error and I
make this mistake a lot myself because when I write down dates I'm used to adding in that leading zero but uh that's not the correct way to pass it in so just do uh for single digits just do
that single digit and you can see that that works now we do have other ways of creating dates also so if I wanted to get today's local date then I'm just
going to call this today and instead of doing this Constructor here I'm just going to do date. today so now I'm just going to go ahead and grab this variable
name here and let's go ahead and print that out so when I print that out you can see that we got the current local date now we also have some methods available to get more information about
our dates so if I wanted to grab just the year month or day then so for example if I wanted to grab just the year I could say today. year and if I
wanted to grab just the day then I could do day now we can also get the day of the week week and there's actually two different ways that we can use this so
we can either use weekday or we can use ISO weekday so if I go ahead and print this out you can see that for one we get
a one and for the other one we get a two so the only difference here is that for
the weekday Monday is zero and Sunday is six and for the iso weekday Monday is 1
and Sunday is 7 so the current day where I am now it is Tuesday so you can see that uh for the weekday we got a one which if Monday is zero then Tuesday
that would be correct and for the iso weekday Monday is one so Tuesday would be two so that's correct also okay so now let's take a look at time Deltas now
time Deltas are simply the difference between two dates or times and they're extremely useful when we want to do operations on our dates or times so for
example let me create a Time Delta one week away which would be seven days so I'm going to do a Time Delta is equal to
date time. time Delta and I'm just going
date time. time Delta and I'm just going to pass in a duration here of days equal to 7 so now I'm going to go ahead and just get rid of these two print
statements here so now that I have this duration of s days I can use this to do some calculations so let's say that I wanted to print out what the date will
be one week from now so what I can do here is I can just do a print and I'm going to print out today plus this time Delta which would be seven days so if I
run that then you can see that it prints out what the date will be 7 days from now now you can also subtract time Deltas also so if I wanted to know what
the date was one week ago then instead of adding on seven days I can subtract 7 days and if I print that out then you can see that it prints out what the date
was one week ago okay so right now we are adding and subtracting a Time Delta from a date and getting another date as
the result now if we instead add or subtract a date from a date then we'll get a Time Delta as the result and so that's kind of important to see the
difference there so if I make a comment here so that we can better visualize this so let me do
time Delta and let me also make another comment here but change a few things around okay so this comment will make what I just said here a little bit
easier to visualize so if we add or subtract a Time Delta from a date then we get another date as a result and if
we add or subtract another date from a date then we'll get a Time Delta as a result so let's go ahead and take a look at an example of this um so let's figure out
how many days there are until my birthday this year so to calculate that we're going to have to do is subtract the current date from the date of my
birthday this year so I'm going to create a new date here called bday I'm going to set that equal to date time.
dat and it's going to be the year 2016 and my birthday is on 9:24 so now I'm going to create another variable here and I'm going to call this
till bday now this is going to be a time Delta once we run this calculation and I'm going to say till bday is equal to
my birthday minus the current day so now if I print out this till bday and run
that you can see that it has 60 days as the total duration between those two dates and if you want to get just the days then you can do the time delta.
days and print that and you can see that that's equal to 60 now you can also use the total seconds here so I'm going to do total seconds and that's a method to
get the number of seconds between these two dates so if I print that out oh and it looks like I forgot to do total seconds so if I print that out then you
can see I have a little more than five m million seconds to go until my birthday okay so now that we have looked at this date time. dat right here now let's look
date time. dat right here now let's look at date time.time and I'm just going to go ahead
time.time and I'm just going to go ahead and set this variable equal to T okay so when we were working with date time. dat
we were only working with year month and day and with date time.time we're going to be working with hours minutes seconds and microc seconds so this isn't going
to include the year the month or the day now by default this doesn't have time zone information so this is still naive but we can specify a time zone using TZ
info if we'd liked and we'll look at some time zones in just a second but for now we're going to create a new time uh so I can create a new local time by
saying date time.time and I'm going to pass in hours minutes seconds and micros seconds so now I'm just going to go ahead and print this out so we can see
what this looks like so you can see that it printed out here in a nice format and just like with the date we can access these attributes individually so if I wanted to just print out the hour then I
can just print out the hour now to be honest I hardly ever use date time.time
because most of the time when I need the time of day I also need the date and that's where date time. dat time comes in so what we had here is we had date
time. dat and that gave us the year
time. dat and that gave us the year month and day without the hours minutes seconds and micros seconds and then we had date
time.time and that gave us the hours
time.time and that gave us the hours minutes and seconds and micros seconds without the year month and the day and the date
time. dat time that's going to give us
time. dat time that's going to give us access to everything so for example if I create a new date time here then I could
pass in all of these so I'll pass in the year of 2016 7 26 then I'll just do 12 for the hours 30 for the minutes 45 for
the seconds and another 100,000 for the milliseconds and I'm going to go ahead and call this DT for date time let's go ahead and print this out so now if I
print this out you can see that it gave us back the entire date and the time so we have the whole date right here and then we have the time here now date
times are great because we have access to just about anything we would need so I can grab the date without the time just by saying dt. date here and that is
a method and vice versa I could grab the time just by doing date time.time and if I run that you can see that we just get the time and on top of that we can still
grab each individual attribute uh like we did before so let's say that I wanted just the year then I can just go ahead and print out the year and just like we
did with the date we can also add and subtract time Delta duration so let me go ahead and recreate that time Delta and the way that we did that was date
time. time Delta and I'm also just going
time. time Delta and I'm also just going to do the days of seven again okay so now instead of printing out just this
date time now I'm going to add on this time Delta and if I print that out you can see that that prints out a week into the future and now with this daytime I
can also use a duration of hours or minutes or whatever so if I was to change this duration instead of days of seven uh let's say I'll do hours and
I'll do 12 hours into the future and if I print that out you can see that my time was set to 12:30 here so by adding 12 hours that carried us over into the
next day and this is 30 minutes past midnight okay so now let's look at some of the alternative Constructors that come with our date time so three of these that are pretty useful that a lot
of people get confused about are today and I'm just going to go ahead and copy these down three different times here and I'm going to call this dt. today I'm
going to call this one dt. now and I'm going to call this one DT UTC now and I'm going to do today and this one will
be date time. now and this one will be UTC now okay so now let me go ahead and print all of these out here before I
describe what each individual one is so let me copy these here and print these out okay so you can see that the top two
here are pretty similar and they would be exactly the same if they had been executed at the same time so these millisecond differences here are just due to the small amounts of time between
when they were executed so if date time.
toay and date time now uh look almost identical here then what is the difference between these so the difference is thatt today Returns the
current local date time with a time zone of none andt now gives us the option to pass in a time zone so if you leave the
time zone empty then these are similar now you might assume here that UTC now since it has UTC in the name of the method that this is a time zone aware
date time and that's actually not true so this gives us the current UTC time but the TZ info is still set to none so nothing that we've done so far has given
us time zone aware date times we have to explicitly set those so that's a good segue into looking at how to use time zones now there's a lot of different ways that we could look at using time zones but I think I'm going to go ahead
and jump directly into showing you how to use Pi TZ now Pi TZ is a third third party package that you have to install using pip now if you have never used a
pip package manager then you can watch my video on how to use that but if you already have it set up then you should be able to jump over to your terminal
and just type in PIP install and that is pi TZ now you might be wondering why I'm not showing you how to work with time zones using the standard library but
even in the python docs here they recommend using pytz so here's the justification for that they say that the standard library has time zone class for
handling arbitrary fixed offsets from UTC and time zone. UTC uh pytz Library brings in this time zone database uh to
Python and its usage is recommended so we could use this time zone class to work with time zones but since pz is pretty easy to use and since it's more useful we may as well go ahead and use
that right off the bat so let's go ahead and go back here to our module and at the top now after you install that using pip now we're just going to import pz so before we make any more
date times here I'm just going to go ahead and clean up some of this and remove a couple of these functions and I'm just going to copy those out for now and let's go ahead and make a new date
time now if you were to go out and read through the documentation for PTZ then you'll see that it's recommended to always work with UTC when dealing with time zones and there's a lot of good
reasons for that that I'm not going to go into detail about here um so let's go ahead and create a time zone aware date
time using UTC now to do this we can just do DT equals datetime do date time and now I can go ahead and plug in all
those values so I'm going to do a year of 2016 7 26 12 for the hours 30 for the minutes 45 for the seconds and I'm going
to go ahead and leave off the milliseconds this time and now to make this time zone aware we can just say TZ info equals
pc. UTC so now let me go ahead and print
pc. UTC so now let me go ahead and print out this date time and we can see what this looks like so now you can see that
our date time has this uh plus 00 on the end now this is the UTC offset now let's get the current UTC time that is also time zone away
so there are two ways that we can do this so remember we have uh now and we also have UTC now uh but first let's
work with now so with daytime. now we
can pass in the time zone so this is instead of TZ info this is actually TZ equals same thing we'll do PI TZ do UTC
and let me go ahead and print that out so that you can see what that looks like datetime now and so this is the current UTC time and you can see the milliseconds added on there and another
way to do this which you might see people do uh online is we also have this UTC now now this doesn't have the option
of passing in the time zone but what we could do is do UTC now which creates a new date time and then we can do a DOT
replace on that TZ info and set that equal to Pi tc. UTC let's go ahead and print this
tc. UTC let's go ahead and print this out so you can see that both of these ways of getting the current UTC time that is time zone aware uh these are
both pretty much the same but I prefer to use this datetime.now with the time zone set because it's a little less typing and it's also slightly easier to
read so I'm going to go ahead and remove that and I don't think I'm going to be using this date time here anymore so I'm going to go ahead and remove that as well okay so now we have the current UTC
time and it's also time zone aware and I'm actually going to go ahead and call this UTC now so that it uh makes a little bit more sense so let's look at
how we can convert this to a different time zone so I'm currently located close to Denver in the United States which is the Mountain Time Zone so if I wanted to
convert this UTC time to my time zone then I could just say I'll call this DT mountain and I'll say DT UTC now do as
time zone and now we can just pass in the time zone that we want and this is going to be pz. time zone and the time zone that I'm
pz. time zone and the time zone that I'm going to pass in here is us- Mountain so now let me go ahead and print this out and we can see the
difference between these two date times so you can see that if I print that out uh the time that it printed out for uh current Mountain time if I look at my
machine here 845 and that's pretty much what we have here and that also has the UTC offset set to -6 which is the difference between my local time and the
UTC time now you might be wondering how I knew to type in a US Mountain here for the pz time zone so pz has a large list
of time zones for you to select from now if you want to look at all of them then you can print them all out by using a for Loop so let's go ahead and do that
so let's do four TZ in pi TZ and the list of those time zones is in a list called all time zones So within this for
Loop I'm just going to print out TZ and let me go ahead and comment out these other print statements for now let's go ahead and run that and bring this up a
bit so you can see that we have a lot of time zones here but if I scroll up a bit then we can see the United States time zone and you know so here we have us
eastern US Mountain uh Pacific and things like that so if you have an idea of what your time zone is then you can just go ahead and search through this
pz. alltime zones list and see
pz. alltime zones list and see specifically what you need to type in in order to get that set correctly okay so now I'm going to go ahead and take this
out and uncommon out these print statements and reprint that okay so what we just did here is we took a time zone
aware date time set to UTC and we converted that to Mountain time but what if we have a naive date time and we want to make that naive date time time zone
aware so for example let me go ahead and create a new local date time that doesn't have that time zone information and remember we can grab the local time
with datetime.now and this isn't time
with datetime.now and this isn't time zone aware right now because we didn't pass in the time zone so now if I go ahead and print out this local date time
here then you can see that I get my local time but that it's not time zone aware So currently I have my local time but it doesn't have any time zone information so if I wanted to convert
this to another time zone so let's say that I wanted to convert this to the United States Eastern time zone so I couldn't just say datetime East equals datetime
mountain. as time zone like we did
mountain. as time zone like we did before so let me go ahead and try this so I'll do pz. time zone and I will pass
in that us Eastern time zone now if I run this then I'm going to get an error and if I scroll up here it says that as
time zone cannot be applied to a naive datetime and that makes sense so in order for me to make my local naive datetime time zone aware I have to run
this time zone localize function so in order to do this first let me comment out that um now to run this time zone
localized function first let me grab the Mountain Time Zone because that is what my current local time is so I'm going to say
pz. time zone and I'm going to pass in
pz. time zone and I'm going to pass in US Mountain so now that I have that time zone I can run its localized method and
pass in my naive date time so I'm just going to set the result to this exact same variable name so I'm going to say
DT mountain is equal to Mountain time zone. localize and now we pass in the
zone. localize and now we pass in the date that we want to localize and that is my datetime Mountain so now if I print this out I'm going to comment out
this for now I'm going to print this out and you can see that now this was a naive date time of my local time and then I ran localize using this Mountain
Time Zone and now what this uh date time it used to be naive and now it is time zone aware so now let's try to run that same command that gave us an error
earlier so if I try to now convert this over to this date time East then I can go ahead and print this out if I save that and run it now you can see that
since our datetime mountain is time unaware that it correctly set that time two hours ahead to the Eastern Time Zone okay so I know that this video is getting a little long but I'd like to
show you all a couple more things here really quick so real quick I'm going to go ahead and set this back to my local datetime that is time zone aware and
then I can get rid of all of this other information here for now just to clean this up a bit okay so I just want to show a couple different ways that you can display these date times so probably
the best way to save these dates or pass them around for internal use would be the iso format and to display these in ISO format it's just as easy as saying
so we'll print this out we'll print out datetime mountain. ISO format now if you're not
mountain. ISO format now if you're not familiar with that format then it can look a little strange but it is an international standard now if you want to print these date times out in a
specific format then you can go to to the python documentation and look at the format codes uh to print these out in just about any way that you'd want so if
I go down here and look at these codes then you can see that they have what the format code is and then the examples so let's say that I wanted to print it out
in the form uh July 26 2016 um so to do that after looking at those format codes you can use this
method called stf time and then pass in the format code so the format code that I want is
percent uppercase B which is the full month percent lowercase D which is a two-digit day then I'm going to put in a comma and then a percent sign uppercase
Y which will be the full year so if I print that then you can see that it prints out July 26 2016 now you don't have to memorize these I've never memorized every time I want to print something out
in a specific format I always go to the documentation and find the format codes that I want and then print them out that way now sometimes you have the opposite sometimes you have a string and you want
to convert that to a date time now you can do that using this date time string P time method so let's go ahead and take
a look at this so I'm going to do a date time string here and I'm just going to copy the exact same date that we we just printed out and I'm going to put this
into a string format so this datetime string right now is currently just a string so I can do string operations on it but there's no way I could do any datetime operations on this so I have to
convert this to a date time if I want to do anything with it so if I wanted to convert this to a date time then I can
just say date time. dat time and then we're going to run this string P time St Str p time and now what we pass in here
is the string that we want to convert and now we have to tell python what format that string is in and we just Ed the same format here so I'm going to go
ahead and grab that and just paste it in so now I'm going to come up here and uh comment out that print statement and I'm just going to print out this date time that we just created from that string
and if I print that out you can see that that string was successfully uh converted over to a date time so just to
make that more clear uh that was St Str F time and that converts a date time to
a string and the St strp time that converts a string to a date time okay so I think that is going to do it for this video I hope that this video cleared up
any confusion when working with dates and times in Python now I should mention that there is a popular python package called arrow that is supposed to be an easier way to work with date times and
maybe I'll try to do a video of that in the near future but I hope that knowing these basics of the built-in datetime module that will allow you to solve most the problems that you come up against but if you do have any questions about
what we covered in this video then just feel free to ask in the comment section below and I'll do my best to answer those if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to Simply like the video
and give it a thumbs up and also it's a huge help to share these videos with one who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section
below uh be sure to subscribe for future videos and thank you all for watching
Loading video analysis...