Home » Python datetime module with examples

Python datetime module with examples

Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Oracle Java Certification
1 Year Subscription

In python to work with date and time objects, you have to import a module called datetime in Python.

This Python datetime module holds different classes to work with dates or to manipulate dates and times.

Learn how to import datetime in Python, work with date and time objects, format datetime, timedelta with practical examples.

To import the datetime module.

import datetime

Methods

Function with Description
time.altzone

The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC. Only use this if daylight is nonzero.

time.asctime([tupletime])

Accepts a time-tuple and returns a readable 24-character string

time.clock( )

Returns the current CPU time as a floating-point number of seconds.

time.ctime([secs])

Like asctime(localtime(secs)) and without arguments is like asctime( )

time.gmtime([secs])

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time.

time.localtime([secs])

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).

time.mktime(tupletime)

Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.

time.sleep(secs)

Suspends the calling thread for secs seconds.

time.strftime(fmt[,tupletime])

Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.

time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

Parses str according to format string fmt and returns the instant in time-tuple format.

time.time( )

Returns the current time instant, a floating-point number of seconds since the epoch.

time.tzset()

Resets the time conversion rules used by the library routines.

Examples

Current Date

In this example, we use the today() method defined in the date class to get a date object containing the current local date.

import datetime

date_object = datetime.date.today()
print(date_object)

Current Date and Time

The datetime classes defines the datetime module. We use the now() method to create a datetime object containing the local date and time.

import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)

Current year, month and day

from datetime import date

# date object of today's date
today = date.today() 

print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Date and time example

import datetime

print ('The Date Today is  :', datetime.datetime.today())

date_today = datetime.date.today()
print (date_today)
print ('This Year   :', date_today.year)
print ('This Month    :', date_today.month)
print ('Month Name:',date_today.strftime('%B'))
print ('This Week Day    :', date_today.day)
print ('Week Day Name:',date_today.strftime('%A'))

datetime.now example

from datetime import datetime
 
dt = datetime.now()
 
print('Date = ', dt)
print('Year from Date        = ', dt.year)
print('Month from Date       = ', dt.month)
print('Day from Date         = ', dt.day)
print('Hour from Date        = ', dt.hour)
print('Minute from Date      = ', dt.minute)
print('Second from Date      = ', dt.second)
print('Microsecond from Date = ', dt.microsecond)
print('Weekday Number from Date = ', dt.weekday())

utcfromtimestamp example

from datetime import datetime
 
tm_stamp = datetime.utcfromtimestamp(123456789)
print('Date  = ', tm_stamp)
 
tm_stamp2 = datetime.utcfromtimestamp(498752356)
print('Date  = ', tm_stamp2)
 
tm_stamp3 = datetime.utcfromtimestamp(1876523564)
print('Date  = ', tm_stamp3)
 
tm_stamp4 = datetime.utcfromtimestamp(2718902192)
print('Date  = ', tm_stamp4)

date functions example

Other date functions

from datetime import datetime
 
dt = datetime.now()
print('Date and Time = ', dt)
 
print('Replace in Date = ', dt.replace(hour = 2))
print('Tzinfo from Date = ', dt.tzinfo)
print('Tzname from Date = ', dt.tzname())
 
print('Timetz from Date = ', dt.timetz())
print('Timestamp from Date = ', dt.timestamp())
print('Time from Date = ', dt.ctime())
print('isoweekday from Date = ', dt.isoweekday())
 
print('astimezone from Date = ', dt.astimezone())
print('utcoffset from Date = ', dt.utcoffset())
print('Daylight Saving from Date = ', dt.dst())

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More