Get current date python datetime

How to Get the Current Date and Time in Python

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

The 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 date and time attributes
Читайте также:  Mr. Camel

Let’s get the current date and time with a datetime.datetime object, as it is easier to extract date and time objects from it. First, let’s import the datetime module:

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:

The 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 

The 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 date() method:

>>> 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 date class:

>>> from datetime import date >>> current_date = date.today() >>> print(current_date) 2019-12-13 

The datetime.date class represents a calendar date. Its year , month , and day attributes can be accessed in the same way we access them on the datetime object.

For example, this print statement gets each attribute, and also uses the weekday() method to get the day of the week:

>>> print("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 year 

Note: The 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 time() method:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

>>> 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.

Like the datetime object, we can access its attributes directly. Here’s an example where we print the current_time in a sentence:

>>> print("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 microseconds 

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 time objects.

Getting the Current Date and Time in Different Timezone

The 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.

Install the pytz library with pip if it’s not available on your computer already:

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 

The 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 time library:

>>> import time >>> print(time.time()) 1576280665.0915806 

The time.time() function returns a float number with the Unix timestamp. You can convert a timestamp to a datetime object using the fromtimestamp() function:

>>> 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 

Conclusion

Pythons built-in 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 today() function.

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 timestamp() method.

Источник

Python Datetime.now() – How to Get Today’s Date and Time

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Python Datetime.now() – How to Get Today's Date and Time

You can use the datetime module in Python to retrieve data about date and time.

In this article, you’ll learn how to use the datetime object from the datetime module to get the current date and time properties.

You’ll also learn how to get the date and time of different locations around the world using the datetime.now() function and the pytz module.

How to Use the datetime Object in Python

In order to make use of the datetime object, you have to first import it. Here’s how:

from datetime import datetime

In the next example, you’ll see how to use the datetime object.

from datetime import datetime current_dateTime = datetime.now() print(current_dateTime) # 2022-09-20 10:27:21.240752

In the code above, we assigned the datetime to a variable called current_dateTime .

When printed to the console, we got the current year, month, day, and time: 2022-09-19 17:44:17.858167 .

Note that we’re able to access the information above using the now() method: datetime.now() .

How to Use the datetime.now() Attributes

In the last section, we retrieved information about the current date and time which included the current year, month, day, and time at that moment.

But the datetime.now() function provides us with extra attributes for extracting individual data.

For example, to get just the current year, you’d do something like this:

from datetime import datetime current_dateTime = datetime.now() print(current_dateTime.year) # 2022

In the example above, we assigned the datetime.now() function to a variable called current_dateTime .

Using dot notation, we attached the year attribute to the variable declared above: current_dateTime.year . When printed to the console, we got 2022.

The datetime.now() function has the following attributes:

Here’s an example of the attributes listed above in use:

from datetime import datetime current_dateTime = datetime.now() print(current_dateTime.year) # 2022 print(current_dateTime.month) # 9 print(current_dateTime.day) # 20 print(current_dateTime.hour) # 11 print(current_dateTime.minute) # 27 print(current_dateTime.second) # 46 print(current_dateTime.microsecond) # 582035

How to Get a Particular Timezone in Python Using datetime.now() and pytz

To get information about different time-zones across the world in Python, you can make use of the datetime.now() function and the pytz module.

Here’s an example that shows how to get the current date and time in Lagos, Nigeria:

from datetime import datetime import pytz datetime_in_Lagos = datetime.now(pytz.timezone('Africa/Lagos')) print(datetime_in_Lagos) # 2022-09-20 12:53:27.225570+01:00

In the code above, we first imported the modules:

from datetime import datetime import pytz 

Then we passed in the pytz object as a parameter to the datetime.now() function:

datetime_in_Lagos = datetime.now(pytz.timezone('Africa/Lagos'))

The pytz object has a timezone attribute that takes information/parameter(s) of the specific time-zone you’re looking for: pytz.timezone(‘Africa/Lagos’) .

With the all_timezones attribute, you can get a list of all the possible time-zones in the pytz library that can be passed in as parameters to the timezone attribute — just like we did in the last example. That is:

from datetime import datetime import pytz all_timezones = pytz.all_timezones print(all_timezones) # [List of all timezones. ]

Summary

In this article, we talked about getting today’s date and time using the datetime.now() function in Python.

We saw some examples that showed how to use the datetime.now() function and its attributes.

Lastly, we saw how to get the date and time in specific locations around the world using the datetime.now() function and the pytz module.

Источник

Оцените статью