Logging, saving records to the database, and accessing files are all common tasks a programmer works on. In each of those cases, date and time play an important role in preserving the meaning and integrity of the data. Programmers often need to engage with date and time.
In this article we will learn how to get the current date and time using Python's builtin datetime module. With that module, we can get all relevant data in one object, or extract the date and time separately.
We will also learn how to adjust our date and time for different timezones. Finally, we'll look at converting
datetime objects to the popular Unix or Epoch timestamps.
Getting the Current Date and Time with datetime
datetime module contains various classes to get information about the date and time:
datetime.date: Stores the day, month and year or a date
datetime.time: Stores the time in hours, minutes, seconds, and microseconds. This information is independent from any date
datetime.datetime: Stores both
Let's get the current date and time with a
datetime.datetime object, as it is easier to extract
time objects from it. First, let's import the
from datetime import datetime
While it looks strange at first, we are getting the
datetime class from the
datetime module, which are two separate things.
We can use the
now() function to get the an object with the current date and time:
current_datetime = datetime.now() print(current_datetime)
Running this file will give us the following output:
now() function gave us an object with all date and time of the moment it was created. When we print it, Python automatically formats the object to a string so it can be read by humans easily. You can read our guide on How to Format Dates in Python to learn various ways to print the time.
You can get individual attributes of the date and time like this:
print(current_datetime.year) # 2019 print(current_datetime.month) # 12 print(current_datetime.day) # 13 print(current_datetime.hour) # 12 print(current_datetime.minute) # 18 print(current_datetime.second) # 18 print(current_datetime.microsecond) # 290623
now() method is perfect for capturing a moment. However, it is redundant when you only care about either the date or the time, but not both. How can we get date information only?
Getting the Current Date
There are two ways to get the current date in Python. In the Python console, we can get the date from a
datetime object with the
from datetime import datetime current_date = datetime.now().date() print(current_date) 2019-12-13
However, it does seem like a waste to initialize a
datetime object only to capture the date. An alternative would be to use the
today() method of the
from datetime import date current_date = date.today() print(current_date) 2019-12-13
datetime.date class represents a calendar date. Its
day attributes can be accessed in the same way we access them on the
For example, this
weekday() method to get the day of the week:
"It's the %dth day of the week, %dth day of the %dth month of the %dth year" % (current_date.weekday()+1, current_date.day, current_date.month, current_date.year)) It's the 5th day of the week, 13th day of the 12th month of the 2019th yearprint(
weekday() method returns an integer between 0 and 6 to represent the day of the week. 0 corresponds to Monday. Therefore, in our example we added 1 in order to print the 5th day of the week (Friday), although the
weekday() method returned 4.
Now that we can get the current date by itself, let's see how we can get the current time
Getting the Current Time
We capture the current time from a
datetime object using the
from datetime import datetime current_time = datetime.now().time() print(current_time) 12:18:18.290623
Unlike retrieving dates, there is no shortcut to capture current the time directly. The
datetime.time class represents a notion of time as in hours, minutes, seconds and microseconds - anything that is less than a day.
datetime object, we can access its attributes directly. Here's an example where we print the
current_time in a sentence:
"It's %d o'clock. To be exact, it's %d:%d and %d seconds with %d microseconds" % (current_time.hour, current_time.hour, current_time.minute, current_time.second, current_time.microsecond)) It's 12 o'clock. To be exact, it's 12:18 and 18 seconds with 290623 microsecondsprint(
By default, the
now() function returns time your local timezone. What if we'd need to convert it to a different one which was set in a user's preference? Let's see how we can provide timezone information to get localized
Getting the Current Date and Time in Different Timezone
now() method accepts a timezone as an argument, so that the
datetime object being generated would be appropriately adjusted. First, we need to get timezone data via the pytz library.
pytz library with
pip if it's not available on your computer already:
pip3 install pytz
Now, let's use
pytz to get the current date and time if we were in Berlin:
import pytz from datetime import datetime tz = pytz.timezone('Europe/Berlin') berlin_current_datetime = datetime.now(tz) print(berlin_current_datetime) 2019-12-14 00:20:50.840350+01:00
berlin_current_datetime would be a
datetime object with all the properties and functions we saw earlier, but now it perfectly matches what it is for someone who lives there.
If you would like to get the time in UTC, you can use the
pytz module like before:
import pytz from datetime import datetime utc_current_datetime = datetime.now(pytz.timezone("UTC")) print(utc_current_datetime) 2019-12-13 23:20:50.840350+00:00
Alternatively, for UTC time you don't have to use the
pytz module at all. The
datetime module has a
timezone property, which can be used like this:
from datetime import datetime, timezone utc_current_datetime = datetime.now(timezone.utc) print(utc_current_datetime) 2019-12-13 23:20:50.840350+00:00
Now that we can convert our dates and times to match different timezones, let's look at how we can convert it to one of the most widely used formats in computing - Unix timestamps.
Converting Timestamps to Dates and Times
Computer systems measure time based on the number of seconds elapsed since the Unix epoch, that is 00:00:00 UTC on January 1st, 1970. It's common for applications, databases, and protocols to use a timestamp in order to display time.
You can get the current timestamp in Python using the
import time print(time.time()) 1576280665.0915806
time.time() function returns a float number with the Unix timestamp. You can convert a timestamp to a
datetime object using the
from datetime import datetime print(datetime.fromtimestamp(1576280665)) 2019-12-13 19:44:25
By default, the
fromtimestamp() returns a
datetime object in your timezone. You can provide a timezone as a second argument if you would like to have it localized differently.
For example, to convert a timestamp to a
datetime object in UTC, you can do this:
from datetime import datetime, timezone print(datetime.fromtimestamp(1576280665, timezone.utc)) 2019-12-13 19:44:25+00:00
Conversely, you can use the
timestamp() method to convert a
datetime object to a valid timestamp:
from datetime import datetime, timezone print(datetime.now(timezone.utc).timestamp()) 1577117555.940705
datetime library allows us to get the current date and time with the
now() function. We can use the returned
datetime object to extract just the date portion or the time portion. We can also get the current date with the
By default, Python creates
datetime objects in our local timezone. If we utilize the
pytz library, we can convert dates and times into different timezones.
Finally, we used the
fromtimestamp() function to take a Unix timestamp to get a
datetime object. If we have a
datetime object, we can get a timestamp using its