Skip to content

Marina Mele's site

Reflections on family, values, and personal growth

Menu
  • Home
  • About
Menu

13 useful tips about Python datetime objects

Posted on March 23, 2014June 19, 2015 by Marina Mele

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 Melé
Marina Mele

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)

Leave a Reply Cancel reply

You must be logged in to post a comment.

Categories

  • Personal Growth and Development
  • Artificial Intelligence
  • Mindful Parenting and Family Life
  • Productivity and Time Management
  • Mindfulness and Wellness
  • Values and Life Lessons
  • Posts en català
  • Other things to learn

Recent Posts

  • BlueSky Social – A Sneak Peek at the Future of Social Media
  • The Incredible Journey of AI Image Generation
  • AI and Fundamental Rights: How the AI Act Aims to Protect Individuals
  • Overcoming Regrets: Finding the Strength to Move Forward
  • Thinking Outside the Box: Creative Problem-Solving with Critical Thinking

RSS

  • Entries RSS
Follow @marina_mele
  • Cookie Policy
  • Privacy Policy
©2023 Marina Mele's site | Built using WordPress and Responsive Blogily theme by Superb
This website uses cookies to improve your experience. If you keep navigating through this website, we'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT