declare

Python Tutorial: Datetime Module - How to work with Dates, Times, Timedeltas, and Timezones



Sharing buttons:

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

and 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

eight 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 timezone 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

timezone 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 dot date 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

date 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 Oh 724 now when you're

creating these dates be sure to just

pass in regular integers as the days and

months with no leading 0 because if we

were to pass in 0 7 here and run that

you can see that this gave us a syntax

error and I make this mistake a lot

myself because when I write down baits

I'm used to adding in that leading 0 but

that's not the correct way to pass it in

so just do 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 dot 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 dot 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 and there's actually two

different ways that we can use this so

we can either use weekday or we can use

I so weekday so if I go ahead and print

this out you can see that for 1 we get a

1 and for the other one we get a 2 so

the only difference here is that for the

weekday Monday is 0 and sunday is 6 and

for the icer weekday Monday is 1 and

sunday is 7 so the current day where I

am now it is Tuesday so you can see that

for the weekday we got a 1 which if

Monday is 0 then Tuesday that would be

correct

and for the I so weekday Monday is 1 so

Tuesday would be 2 so that's correct

also ok 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 dot time

Delta and I'm just going to pass in a

duration here of days equal to seven

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

seven 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 seven days from

now now you can also subtract time

Delta's also so if I wanted to know what

the date was one week ago then instead

of adding on seven days I can subtract

seven 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 for

my 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 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

d-day I want to set that equal to date

time dot date and it's going to be the

year 2016 and my birthday is on 924 so

now I'm going to create another variable

here and I'm kind of 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 - 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

dot days and print that 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 5

million seconds to go until my birthday

ok so now that we have looked at this

date time dot date right here now let's

look at date time dot 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 dot date we were only

working with year month and day and with

date time dot time we're going to be

working with hours minutes seconds and

microseconds so this isn't going to

include the year the month or the day

now by default this doesn't have

timezone 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 so I can create a new local time a

saying date time dot time and I'm going

to pass in hours minutes seconds and

microseconds 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 that date time

comes

so what we had here is we had date time

dot date and that gave us the Year month

and day without the hours minutes

seconds and microseconds and then we had

date time dot time and that gave us the

hours minutes and seconds and

microseconds without the Year month and

the day and the date time dot date/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 hundred thousand 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 dot date here and that

is a method and vice-versa I could grab

the time just by doing date time dot

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 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 dot 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 day time I can also use a

duration of hours or minutes or whatever

so if I was to change this duration

instead of days of sub

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 our dot 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 dot today I'm

going to call this one DT dot 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 dot now and this one

will be dot 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 day time dot today and date time

now look almost identical here then what

is the difference between these so the

difference is that dot today returns the

current local date time with a timezone

of none and dot 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

dot 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 T Z now PI TZ is a third

party package that you have to install

using pip now if you have never used the

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 Doc's here they recommend

using pi TZ so here's their

justification for that they say that the

standard library has timezone class for

handling arbitrary fixed offsets from

UTC and timezone UTC PI TZ library

brings in this time zone database to

Python and it's usage is recommended so

we could use this time zone class to

work with time zones but since pi TZ 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 PI TZ

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 pi TZ 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 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 date/time dot

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 PI T Z dot 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 plus zero zero on the end now this

is the UTC offset now let's get the

current UTC time that is also timezone

aware so there are two ways that we can

do this so remember we have dot now and

we also have dot UTC now

but first let's work with dot now so

with daytime dot now we can pass in the

timezone so this is instead of TZ info

this is actually T Z equals same thing

we'll do PI T Z dot UTC and let me go

ahead and print that out so that you can

see what that looks like

date time now and so this is the current

UTC time and you can see the

milliseconds added on there and another

way to do this what you might see people

do on line is we also have this dot UTC

now now this doesn't have the option of

passing in the timezone 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 T C dot 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 times unaware

these are both pretty much the same but

I prefer to use this date time dot now

with the timezone 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 ok so now

we have the current UTC time and it's

also timezone aware and I'm actually

going to go ahead and call this UTC now

so that it 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

and I could just say I'll call this DT

Mountain and I'll say DT UTC now dot as

time zone and now we can just pass in

the time zone that we want and this is

going to be PI T Z dot 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

the time that it printed out for a

current Mountain time if I look at my

machine here 8:45 and that's pretty much

what we have here and that also has the

UTC offset set to negative six which is

the difference between my local time and

the UTC time now you might be wondering

how I knew to type in US Mountain here

for the PI TZ time zone so PI TZ 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 for TZ in

PI T Z 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

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 pi TZ dot all time zones

list and see specifically what you need

to type in in order to get that set

correctly ok so now I'm going to go

ahead and take this out and uncomment

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 date time dot 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 date time east equals

date time mountain thought as time zone

like we did before so let me go ahead

and try this so I'll do PI TZ that time

zone and I will pass in that u.s.

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 date time

and that makes sense

so in order for me to make my local

naive date time time zone aware I have

to run this time zone localized function

so in order to do this first let me

comment out that 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 PI T Z dot 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 dot

localize and now we pass in the date

that we want to localize and that is my

date time 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 localized using this mountain time

zone and now what this date time it used

to be naive and now it is times unaware

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

date time mountain is times 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 date time that is

times unaware 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 an ISO

format it's just as easy as saying so

will print this out will print out date

time Mountain dot 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 the

Python documentation and look at the

format codes 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 example so

let's say that I wanted to print it out

in the form July 26 2016 so to do that

after looking at those format codes you

can use this method called STR

F time and then pass in the format code

so the format code that I want is

percent uppercase B which is the full

month % lowercase D which is a two-digit

day then I'm going to put in a comma and

then a % 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 these 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 just

print it out and I'm going to put this

into a string format

so this date/time 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 date/time 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 and I can just say date/time

dot date/time and then we're going to

run this string P time 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 use 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 go up here and comment out that

print statement and I'm just going to

print out the state time that we just

created from that string and if I print

that out you can see that that string

was successfully converted over to a

date/time so just to make that more

clear that was STR F time and that

converts a date/time to a string and the

STR P time that converts

a string to a date-time okay so I think

that it's 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 date/time

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 I

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

anyone 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 be sure to subscribe for

future videos and thank you all for

watching