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:
>>> import datetime >>> now = datetime.datetime.now() >>> today = now.date() >>> moment = now.time()
If you print each of these items you’ll get something like:
>>> now datetime.datetime(2014, 3, 23, 16, 38, 46, 271475) >>> today datetime.date(2014, 3, 23) >>> moment datetime.time(16, 38, 46, 271475)
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:
>>> today = datetime.date.today() >>> moment = datetime.datetime.now().time() >>> now = datetime.datetime.combine(today, moment)
3. Another interesting object is the timedelta object, which can be used to sum or subtract a number of days:
>>> yesterday = today - datetime.timedelta(1)
Or it can store a datetime difference between two datetime objects:
>>> delta = yesterday - today
4. Date objects have three mandatory arguments (you can change its order by using keys):
>>> my_date = datetime.date(1984, 6, 24) >>> my_date = datetime.date(day=24, year=1984, month=6)
5. Time objects don’t have mandatory arguments. These tree statements are equivalent:
>>> my_time = datetime.time() >>> my_time = datetime.time(0,0) # first argument hour, second minute >>> my_time = datetime.time(hour=0, minute=0)
6. Datetime objects have the same mandatory arguments as the date objects:
>>> my_datetime = datetime.datetime(year=1984, month=6, day=24) # Time is set to 0:00 >>> my_other_datetime = datetime.datetime(1984, 6, 24, 18, 30) >>> my_other_datetime = datetime.datetime(year=1984, month=6, day=24, hour=18, minute=30)
7. Change one datetime object to obtain another using the replace method:
>>> another_datetime = my_datetime.replace(year=2014, month=1)
8. Obtain a datetime object representing the epoch: 01-01-1970:
>>> epoch = datetime.datetime.utcfromtimestamp(0)
9. Obtain the number of days and seconds between the epoch and now, or the total number of seconds that have passed:
>>> delta = now - epoch >>> days = delta.days >>> seconds = delta.seconds >>> total_seconds = delta.total_seconds()
10. Recover now using the number of seconds since epoch using the utcfromtimestamp method:
>>> now = datetime.datetime.utcfromtimestamp(seconds)
11. Write a date object as “1984-06-24”:
>>> string_date = str(my_date)
12. Recover a date object from a string like “1984-06-24”:
>>> my_date = datetime.date(*[int(i) for i in string_date.split("-")])
13. Write a date object with a custom string format – the strftime method:
>>> string_date = my_date.strftime('%m/%d/%Y') # This writes "06/24/1984"
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! 🙂
Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)