Who does not face problems when without your gadgets or your phone to see the current time. I have faced such problems, when I’ve gone out and in the process forgot to take my mobile along. This article, is all about time, date, timezones and also the current time in Python. Time conversions can be quite boring and tedious, but Python is a great respite. So, now let us get right into understanding the concepts of date and time in Python.
The pendulum Module
Pendulum is a timezone library that eases the datetime manipulation. It is similar to the datetime module, which we will see a little later. The pendulum module also offers a now() method that returns the local date and time.
Pendulum can be easily installed using the PIP command:
pip install pendulum
import pendulum time = pendulum.now() print(time)
As mentioned earlier, the now() method returns the current date and time as we can see from the above output.
Current Date and Time in Python
Python also offers quite a lot of features for reliability and cross-platform code usability. In most of the cases, thus, the user needs date or time for a specific timezone and using some modules like pytz and pendulum makes working in such an environment much easier.
Note, that the pytz module brings the Olson tz database into Python. It allows for accurate and cross platform timezone calculations.
pip install pytz
Now let us take an example where we try to get and then print date as well as time for different timezones. This is going to be done using both the
import pytz from datetime import datetime utc = pytz.timezone('UTC') pst = pytz.timezone('America/Los_Angeles') ist = pytz.timezone('Asia/Calcutta') print("Using pytz Module:") print('Current Date and Time in UTC =', datetime.now(utc)) print('Current Date and Time in PST =', datetime.now(pst)) print('Current Date and Time in IST =', datetime.now(ist)) import pendulum utc1 = pendulum.timezone('UTC') pst1 = pendulum.timezone('America/Los_Angeles') ist1 = pendulum.timezone('Asia/Calcutta') print("Using pendulum Module:") print('Current Date Time in UTC =', datetime.now(utc1)) print('Current Date Time in PST =', datetime.now(pst1)) print('Current Date Time in IST =', datetime.now(ist1))
Using pytz Module: Current Date and Time in UTC = 2021-04-26 15:44:53.074040+00:00 Current Date and Time in PST = 2021-04-26 08:44:53.090041-07:00 Current Date and Time in IST = 2021-04-26 21:14:53.126043+05:30 Using pendulum Module: Current Date Time in UTC = 2021-04-26 15:44:56.888258+00:00 Current Date Time in PST = 2021-04-26 08:44:56.889258-07:00 Current Date Time in IST = 2021-04-26 21:14:56.889258+05:30
- For both the cases, firstly we use the timezone() function defined for both pytz and pendulum modules while passing the required timezone
- Then we pass these timezone objects to the now() function. . The method returns an accurate date and time for the given timezone.
The “datetime” Module — Current Time in Python
This module provides for classes for manipulating dates and times in Python.
In the example provided below, we try to execute various operations on date and time. Like fetching the current date and current time and other such things, using methods and functions like today(), now(), time, etc.
Miscellaneous Examples using the datetime module
import time from datetime import datetime def main(): print('*** Get Current date & timestamp using datetime.now() ***') # Returns a datetime object containing the local date and time dateTimeObj = datetime.now() # Access the member variables of datetime object to print date & time information print(dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day) print(dateTimeObj.hour, ':', dateTimeObj.minute, ':', dateTimeObj.second, '.', dateTimeObj.microsecond) print(dateTimeObj) # Converting datetime object to string timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)") print('Current Timestamp : ', timestampStr) timestampStr = dateTimeObj.strftime("%H:%M:%S.%f - %b %d %Y ") print('Current Timestamp : ', timestampStr) print('*** Fetch the date only from datetime object ***') # get the date object from datetime object dateObj = dateTimeObj.date() # Print the date object print(dateObj) # Access the member variables of date object to print print(dateObj.year, '/', dateObj.month, '/', dateObj.day) # Converting date object to string dateStr = dateObj.strftime("%b %d %Y ") print(dateStr) print('*** Fetch the time only from datetime object ***') # get the time object from datetime object timeObj = dateTimeObj.time() # Access the member variables of time object to print time information print(timeObj.hour, ':', timeObj.minute, ':', timeObj.second, '.', timeObj.microsecond) # It contains the time part of the current timestamp, we can access it's member variables to get the fields or we can directly print the object too print(timeObj) # Converting date object to string timeStr = timeObj.strftime("%H:%M:%S.%f") print(timeStr) print('*** Get Current Timestamp using time.time() ***') # Get the seconds since epoch secondsSinceEpoch = time.time() print('Seconds since epoch : ', secondsSinceEpoch) # Convert seconds since epoch to struct_time timeObj = time.localtime(secondsSinceEpoch) print(timeObj) # get the current timestamp elements from struct_time object i.e. print('Current TimeStamp is : %d-%d-%d %d:%d:%d' % ( timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec)) # It does not have the microsecond field print('*** Get Current Timestamp using time.ctime() *** ') timeStr = time.ctime() print('Current Timestamp : ', timeStr) if __name__ == '__main__': main()
*** Get Current date & timestamp using datetime.now() *** 2021 / 4 / 26 20 : 24 : 10 . 371305 2021-04-26 20:24:10.371305 Current Timestamp : 26-Apr-2021 (20:24:10.371305) Current Timestamp : 20:24:10.371305 - Apr 26 2021 *** Fetch the date only from datetime object *** 2021-04-26 2021 / 4 / 26 Apr 26 2021 *** Fetch the time only from datetime object *** 20 : 24 : 10 . 371305 20:24:10.371305 20:24:10.371305 *** Get Current Timestamp using time.time() *** Seconds since epoch : 1619448851.1463068 time.struct_time(tm_year=2021, tm_mon=4, tm_mday=26, tm_hour=20, tm_min=24, tm_sec=11, tm_wday=0, tm_yday=116, tm_isdst=0) Current TimeStamp is : 26-4-2021 20:24:11 *** Get Current Timestamp using time.ctime() *** Current Timestamp : Mon Apr 26 20:24:11 2021
Through this post, we have thus, got ourselves a deep understanding of the various modules concerning the date and time and its various functions and methods. We also, saw how to install and work with various libraries like pytz, pendulum and datetime. Thus, now I suppose and hope that the topic at hand is quite clear to you. Since, we have covered the topic in great depth with the help of ample interesting examples.