Skip to content

Working with Dates and Times

Working with Dates and Times

Dates and times are items that most people work with quite a bit. Society bases almost everything on the date and time that a task needs to be or was completed. We make appointments and plan events for specific dates and times. Most of our day revolves around the clock. Because of the time-

oriented nature of humans, it’s a good idea to look at how Python deals with interacting with dates and time (especially storing these values for later use). As with everything else, computers understand only numbers — the date and time don’t really exist.

 

To work with dates and times, you need to perform a special task in Python. When writing computer books, chicken-and-egg scenarios always arise, and this is one of them. To use dates and times, you must issue a special import

 

 

datetime command. Technically, this act is called importing a module, and you learn more about it in Chapter 10. Don’t worry how the command works right now — just use it whenever you want to do something with date and time.

 

Computers do have clocks inside them, but the clocks are for the humans using the computer. Yes, some software also depends on the clock, but again, the emphasis is on human needs rather than anything the computer might require. To get the current time, you can simply type datetime.datetime. now( ) and press Enter. You see the full date and time information as found on your computer’s clock (see Figure 5-6).

 

 

 

Figure 5-6: Get the cur­ rent date and time using the now() command.

 

 

You may have noticed that the date and time are a little hard to read in the existing format. Say that you want to get just the current date, in a readable format. It’s time to combine a few things you discovered in previous sections to accomplish that task. Type str(datetime.datetime.now( ).date( )) and press Enter. Figure 5-7 shows that you now have something a little more usable.

 

 

Figure 5-7: Make the date and time more readable using the str()

command.

 

 

Interestingly enough, Python also has a time() command, which you can use to obtain the current time. You can obtain separate values for each of the components that make up date and time using the day, month, year, hour, minute, second, and microsecond values. Later chapters help you under- stand how to use these various date and time features to keep application users informed about the current date and time on their system.