DEV Community

Cover image for Working with Date and Time in Python
Guilherme Haynes Howe
Guilherme Haynes Howe

Posted on

Working with Date and Time in Python

Say dev, how are you?

In the last week, I took a job where I needed to calculate days and hours with Python. With some Google searches I came up with several results, some really good and others like "WTF .-.".

I soon thought to myself, and I said, "I will research how Python works with hours and develop its own algorithm for that", with some research in the python documentation I found that it is easier than I imagined to be working with date and time.

Introduction

Primeiro criamos nosso arquivo date-hour.py
In python we have the datetime module that provides various date and time manipulation objects, such as date, time, datetime, timedelta, tzinfo and timezone. In this post we will talk about datetime and timedelta.

Datetime

Combining all the date and time attributes, it returns a tuple like the one below:

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Enter fullscreen mode Exit fullscreen mode

For example, returning a current date:

2021-01-24 17:04:18.329567
Enter fullscreen mode Exit fullscreen mode

Its default format is:

  • Year: 4 Digits
  • Month: 2 Digits
  • Day: 2 Digits
  • Hour: 2 Digits
  • Minute: 2 Digits
  • Seconds: 2 Digits + 6 Digits (to differentiate microseconds)

Timedelta

Represents the duration or the difference between two dates or times. It can be represented as follows:

timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Enter fullscreen mode Exit fullscreen mode

For example, returning a difference of 2 hours:

2:00:00
Enter fullscreen mode Exit fullscreen mode

Putting hands in the dough

After presenting the objects we are going to work on, we will start to do some tests. I will comment line by line on what is happening, and in the end, post the result of everything.

First we create our date-hour.py file:

from datetime import datetime, timedelta
now = datetime.now()
print("Tupla de Datetime: " + str(now))
td = timedelta(hours=2)
print("Time delta: " + str(td) + "\n")
print("Hora Atual " + str(now))
print("+2 horas " + str(now + td))
print("-2 horas " + str(now - td))
view raw date-hour.py hosted with ❤ by GitHub
  • Line 1: I import datetime and timedelta from the datetime module
  • Line 3: I take the current datetime, saving it in the variable now
  • Line 5: Black the tuple generated on the screen
  • Line 7: I generated a 2-hour timedelta and saved it in the td variable
  • Line 10: I entered the current time
  • Line 11: I printed the sum of the current time and the timedelta
  • Line 12: I subtracted the current time with the timedelta

Output of the above commands:

Datetime tuple: 2021-01-24 17:39:28.446383
Timedelta: 2:00:00

Current Time 2021-01-24 17:39:28.446383
+2 hours 2021-01-24 19:39:28.446383
-2 hours 2021-01-24 15:39:28.446383
Enter fullscreen mode Exit fullscreen mode

Until the next post <3

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️