Blog

Python DateTime with Example

  • (4.0)
  •   |   414 Ratings

Introduction:

Python is a powerful programming language that has started regaining its fame for its usage in the Data Science along with the latest technologies like R and etc. Having said that, let us take a look at the tiny winy bits of concepts to get ourselves stronger in this programming language.

In this article, we will try to understand the concept of datetime in Python programming language. To provide you a better understanding on what datetime can be used for in Python programming language, take a look at the following section.

Python datetime:

Python provides a package datetime, which contains in built functions and classes that enables you to manipulate with dates or times individually or as a single entity. There are two kinds of date and time objects that are available with Python – naïve and aware. An aware object has enough details (such as day light savings, time zone and etc) to locate itself in relation with the other aware objects and on the other hand, naïve objects are the ones that do not hold enough details to relate with other objects.

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

With this little background knowledge, let’s get down to business in understanding the classes provided by Python. Starting with date classes:

  • Class datetime.date : Returns a naïve date object, provides attributes such as year, month & day
  • Class datetime.time : Returns a time object and also provides attributes such as hour, minute, second, microsecond and tzinfo
  • Class datetime.datetime : A combination of both date and time, provides attributes year, month, day, hour, minute, second, microsecond, tzinfo
  • Class datetime.timedelta : Provides the difference of two date, time or datetime objects to microsecond resolution
  • Class datetime.tzinfo : Is an abstract class for providing time zone information

Related Page: Loops - Python

Let’s now look at a small example on how to access today’s date in Python using the classes provided earlier:

Now look at a small example to display the current local time:

Getting the formatted time from Python is a bit tricky, uses more than one function at once to achieve what we want to show in a single line of code. The best method available from Python is to use asctime() method.

Let us look at the various methods and attributes provided by the time class:

  • time.altzone : This is to be used only when the daylight savings is zero

  • time.asctime([tupletime]) : This method accepts a tuple-time and returns a very well readable string as like this – ‘Mon Aug 28 20:25:14 2017’

  • time.clock() : Returns the current CPU’s time as a floating point number of seconds. On a computational costs approach, this method is preferred over time.time().

  • time.ctime([secs]) : Just like time.asctime()

  • time.gmtime([secs]) : Accepts an instant expressed (seconds) since the epoch and in return, gives time-tuple t in UTC time zone.

  • time.localtime([secs]) : Just like time.gmtime(secs)

  • time.sleep(secs) : Puts the calling thread on sleep for the number of seconds specified in the command

  • time.strftime(fmt[,tupletime]) : Takes an instance as input and returns a string representing the instant in the format provided to the command above.

  • time.strptime(str,fmt=’%a %b %d %H:%M:%S %Y’) : Parses the string as per the format provided and returns the instance in a time-tuple format.

  • time.time() : Returns the current time instant

Frequently Asked Python Interview Questions & Answers

Let us now look at the Calendar class and also as an example, let us look at the month of August 2017.

Now let us take a look at the functions provided by the Calendar class:

  • calendar.firstweekday() : This function returns the current weekday starting each week. By default, when calendar is first imported, this is 0 – Monday by default.

  • calendar.isleap(year) : This function is going to return true if the year passed as an argument is a leap year and returns false if it is a non-leap year.

  • calendar.leapdays(y1,y2) : This function is going to return the total number of leap days between the years specified within the range of y1 and y2.

  • calendar.monthrange(year,month) : This function is going to return a list of lists of ints. Each sublist denotes a week.

  • calendar.setfirstweekday(weekday) : This function is going to set a specific weekday code as a week-day.

  • calendar.timegm(tupletime) : This is exactly the opposite of time.gmtime(). This function accepts a time-tuple and returns a floating point number of seconds since the epoch.

  • calendar.weekday(year,month,day) : This function returns the week-day code of the date specified by the input parameters to this function. 0 being Monday and progressing until 6, which is being a Sunday.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Conclusion:

In this article, we have seen what cases datetime can be used and why are they used in Python programming language. We have also tried to take a deeper look into the concept with various examples as well.

Hope that you were clear with the concepts after going through this detailed article, please do comment if you have any suggestions to make


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules