13 useful tips about Python datetime objects

The Python datetime library provides several useful objects to manipulate times and dates. I’ve been using them a lot lately, and I want to share some useful operations that might be useful to you as well ūüėČ

You can find a video version of this post at the bottom of the page ūüôā

1. First, let’s import the datetime library and create three different kind of objects:
date object: stores the date
time object: stores the time
datetime object: stores both the date and the time

If we create the datetime object first, we can extract its date and time and create the respective objects:

If you print each of these items you’ll get something like:

Where you can see that the time is 16h 46min and 46.171475 seconds, and today is March 23rd, 2014.

2. You can also create a date and time objects and obtain a datetime object using the combine method:

3. Another interesting object is the timedelta object, which can be used to sum or subtract a number of days:

Or it can store a datetime difference between two datetime objects:

4. Date objects have three mandatory arguments (you can change its order by using keys):

5.¬†Time¬†objects don’t have mandatory arguments. These tree statements are equivalent:

6. Datetime objects have the same mandatory arguments as the date objects:

7. Change one datetime object to obtain another using the replace method:

8. Obtain a datetime object representing the epoch: 01-01-1970:

9. Obtain the number of days and seconds between the epoch and now, or the total number of seconds that have passed:

10. Recover now using the number of seconds since epoch using the utcfromtimestamp method:

11. Write a date object as “1984-06-24”:

12. Recover a date object from a string like “1984-06-24”:

13. Write a date object with a custom string format – the strftime method:

You can also check this video version made by Webucator.¬†Don’t forget to visit their website to check their Python courses¬†ūüôā

Hope it’s useful! ūüôā

Google+TwitterLinkedInFacebookReddit

Please, add +Marina Mele in your comments. This way I will get a notification email and I will answer you as soon as possible! :-)