99teachspot - Python - Date & Time (2024)

A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times.

What is Tick?

Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).

There is a populartimemodule available in Python which provides functions for working with times, and for converting between representations. The functiontime.time()returns the current system time in ticks since 12:00am, January 1, 1970(epoch).

Example

#!/usr/bin/pythonimport time; # This is required to include time module.ticks = time.time()print "Number of ticks since 12:00am, January 1, 1970:", ticks

This would produce a result something as follows −

Number of ticks since 12:00am, January 1, 1970: 7186862.73399

Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows.

What is TimeTuple?

Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −

IndexFieldValues
04-digit year2008
1Month1 to 12
2Day1 to 31
3Hour0 to 23
4Minute0 to 59
5Second0 to 61 (60 or 61 are leap-seconds)
6Day of Week0 to 6 (0 is Monday)
7Day of year1 to 366 (Julian day)
8Daylight savings-1, 0, 1, -1 means library determines DST

The above tuple is equivalent tostruct_timestructure. This structure has following attributes −

IndexAttributesValues
0tm_year2008
1tm_mon1 to 12
2tm_mday1 to 31
3tm_hour0 to 23
4tm_min0 to 59
5tm_sec0 to 61 (60 or 61 are leap-seconds)
6tm_wday0 to 6 (0 is Monday)
7tm_yday1 to 366 (Julian day)
8tm_isdst-1, 0, 1, -1 means library determines DST

Getting current time

To translate a time instant from aseconds since the epochfloating-point value into a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all nine items valid.

#!/usr/bin/pythonimport time;localtime = time.localtime(time.time())print "Local current time :", localtime

This would produce the following result, which could be formatted in any other presentable form −

Local current time : time.struct_time(tm_year=2013, tm_mon=7, tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)

Getting formatted time

You can format any time as per your requirement, but simple method to get time in readable format is asctime() −

#!/usr/bin/pythonimport time;localtime = time.asctime( time.localtime(time.time()) )print "Local current time :", localtime

This would produce the following result −

Local current time : Tue Jan 13 10:17:09 2009

Getting calendar for a month

The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ) −

#!/usr/bin/pythonimport calendarcal = calendar.month(2008, 1)print "Here is the calendar:"print cal

This would produce the following result −

Here is the calendar: January 2008Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 1314 15 16 17 18 19 2021 22 23 24 25 26 2728 29 30 31

ThetimeModule

There is a populartimemodule available in Python which provides functions for working with times and for converting between representations. Here is the list of all available methods −

Sr.No.Function with Description
1time.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 (as in Western Europe, including the UK). Only use this if daylight is nonzero.

2time.asctime([tupletime])

Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.

3time.clock( )

Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time().

4time.ctime([secs])

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

5time.gmtime([secs])

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note : t.tm_isdst is always 0

6time.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).

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

8time.sleep(secs)

Suspends the calling thread for secs seconds.

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

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

11time.time( )

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

12time.tzset()

Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.

Let us go through the functions briefly −

There are following two important attributes available with time module −

Sr.No.Attribute with Description
1

time.timezone

Attribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).

2

time.tzname

Attribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively.

ThecalendarModule

The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.

By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday() function.

Here is a list of functions available with thecalendarmodule −

Sr.No.Function with Description
1

calendar.calendar(year,w=2,l=1,c=6)

Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.

2

calendar.firstweekday( )

Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.

3

calendar.isleap(year)

Returns True if year is a leap year; otherwise, False.

4

calendar.leapdays(y1,y2)

Returns the total number of leap days in the years within range(y1,y2).

5

calendar.month(year,month,w=2,l=1)

Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.

6

calendar.monthcalendar(year,month)

Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.

7

calendar.monthrange(year,month)

Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.

8

calendar.prcal(year,w=2,l=1,c=6)

Like print calendar.calendar(year,w,l,c).

9

calendar.prmonth(year,month,w=2,l=1)

Like print calendar.month(year,month,w,l).

10

calendar.setfirstweekday(weekday)

Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).

11

calendar.timegm(tupletime)

The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.

12

calendar.weekday(year,month,day)

Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).

Other Modules & Functions

If you are interested, then here you would find a list of other important modules and functions to play with date & time in Python −

99teachspot - Python - Date &amp; Time (2024)

FAQs

How to pass date to datetime in Python? ›

Convert Date To Datetime In Python Using datetime.

It initializes a string variable (MyDate) with the date “2003-12-17” and then creates a datetime object (DateTime) by parsing the string using the specified format (“%Y-%m-%d”), with the default time set to midnight.

How do you manipulate date and time in Python? ›

datetime includes two methods, strptime() and strftime(), for converting objects from strings to datetime objects and vice versa. strptime() can read strings with date and time information and convert them to datetime objects, and strftime() converts datetime objects back into strings.

How to read date and time in Python? ›

Using the Datetime Module

The datetime module's now() function returns the current time as well as the date. The datetime. now() function returns the current local time and date. It displays datetime in the YYYY-mm-dd hh:mm:ss.

How to parse date time in Python? ›

  1. import time.
  2. def convert(datetime_str):
  3. datetime_str = time.mktime(datetime_str)
  4. format = "%b %d %Y %r" # The format.
  5. dateTime = time.strftime(format, time.gmtime(datetime_str))
  6. return dateTime.
  7. date_time = (2000, 5, 5, 10, 7, 00, 1, 48, 0)
  8. print(convert(date_time))

How do I specify a date in datetime in Python? ›

In certain cases, we will want to create a custom date instead of just displaying the current date. In those cases, we can use the datetime() class constructor of the Python datetime module. This Python datetime() class constructor requires three parameters to create a date, that is, year, month, and day.

How to convert string yyyy mm dd to datetime in Python? ›

Convert a String to a datetime Object in Python Using datetime. strptime()
  1. %Y: 4-digit year.
  2. %y: 2-digit year.
  3. %m: 2-digit month (01-12)
  4. %d: 2-digit day of the month (01-31)
  5. %H: 2-digit hour (00-23)
  6. %M: 2-digit minute (00-59)
  7. %S: 2-digit second (00-59)
Mar 1, 2023

How to set timestamp to date in Python? ›

Converting timestamp to datetime

We may use the datetime module's fromtimestamp() method to convert the timestamp back to a datetime object. It returns the POSIX timestamp corresponding to the local date and time, as returned by time. time().

What is the format of datetime now in Python? ›

datetime. now() method contains the year, month, day, hour, minute, second, and microsecond (expressed as YYYY-MM-DD hh:mm:ss. ffffff ). It also accepts an optional time_zone parameter, which is set to None by default.

How to use datetime function in Python? ›

How to Use Python's datetime
  1. combine() import datetime # (hours, minutes) start_time = datetime.time(7, 0) # (year, month, day) start_date = datetime.date(2015, 5, 1) # Create a datetime object start_datetime = datetime.datetime.combine( start_date, start_time) ...
  2. timedelta. ...
  3. Timestamps. ...
  4. weekday() ...
  5. Date strings.
Jun 17, 2019

How to extract date and time from timestamp in Python? ›

Convert to Datetime Use the fromtimestamp() function to convert the timestamp to a datetime object. Display the Result Finally, print or manipulate the converted datetime object as needed. Now you have successfully converted a timestamp to a datetime object in Python!

What is the difference between date and datetime in Python? ›

In summary, use date to represent dates without time, and datetime to represent a specific point in time inclusive of both date and time. Checking Object Type: To check the type of an object, you can use the built-in type() function or the isinstance() function.

What is the default format for datetime in Python? ›

Formatting and Parsing

The default string representation of a datetime object uses the ISO 8601 format (YYYY-MM-DDTHH:MM:SS. mmmmmm). Alternate formats can be generated using strftime().

How do you pass a date to a Python script? ›

To validate if a string is a valid date input, you need to call the Date() constructor and pass the string as its argument . Note that the Date() constructor requires you to pass a date in the format of YYYY/MM/DD or MM/DD/YYYY . If you pass a date in DD/MM/YYYY format, the contructor also returns an Invalid Date.

How do you pass the current date in Python? ›

Prog1.py
  1. import datetime.
  2. dt = datetime.datetime.now()
  3. print ("Current date and time is = %s" % dt)
  4. print ("Date and time in ISO Format = %s" % dt.isoformat())
  5. print ("Current year = %s" %dt.year)
  6. print ("Current month is = %s" %dt.month)
  7. print ("Current date (day) = %s" %dt.day )

How to format date in Python using datetime? ›

To convert a datetime object into a string using the specified format, use datetime. strftime(format). The format codes are standard directives for specifying the format in which you want to represent datetime. The %d-%m-%Y%H:%M:%S codes, for example, convert dates to dd-mm-yyyy hh:mm:ss format.

How to convert date to timestamp in Python? ›

Convert date string to timestamp Using timetuple()

Then we use strptime method. This method takes two arguments: First argument is the string format of the date and time. Second argument is the format of the input string.

References

Top Articles
First, pasta. Then, pavlova. This restaurant on Nicholson Drive lets you build both options.
Married People Confess The Brutally Honest Things That Shocked Them About Marriage
Pixel Speedrun Unblocked 76
Valley Fair Tickets Costco
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
Optimal Perks Rs3
Apply A Mudpack Crossword
270 West Michigan residents receive expert driver’s license restoration advice at last major Road to Restoration Clinic of the year
Gina's Pizza Port Charlotte Fl
R Tiktoksweets
Cool Math Games Bucketball
House Party 2023 Showtimes Near Marcus North Shore Cinema
Gon Deer Forum
Steamy Afternoon With Handsome Fernando
How to Create Your Very Own Crossword Puzzle
Uconn Health Outlook
Best Transmission Service Margate
Jail View Sumter
Who is Jenny Popach? Everything to Know About The Girl Who Allegedly Broke Into the Hype House With Her Mom
Mythical Escapee Of Crete
Kohls Lufkin Tx
Unable to receive sms verification codes
Garden Grove Classlink
Encore Atlanta Cheer Competition
Lawrence Ks Police Scanner
Fastpitch Softball Pitching Tips for Beginners Part 1 | STACK
The value of R in SI units is _____?
Urban Blight Crossword Clue
Song That Goes Yeah Yeah Yeah Yeah Sounds Like Mgmt
Gabrielle Enright Weight Loss
Yoshidakins
Santa Cruz California Craigslist
Wattengel Funeral Home Meadow Drive
Www Craigslist Com Brooklyn
Lake Kingdom Moon 31
Www.craigslist.com Waco
Thor Majestic 23A Floor Plan
Courtney Roberson Rob Dyrdek
Lyndie Irons And Pat Tenore
Nami Op.gg
Wordle Feb 27 Mashable
My Eschedule Greatpeople Me
Child care centers take steps to avoid COVID-19 shutdowns; some require masks for kids
Perc H965I With Rear Load Bracket
RubberDucks Front Office
Conan Exiles Colored Crystal
Ajpw Sugar Glider Worth
Suppress Spell Damage Poe
Craiglist.nj
Gelato 47 Allbud
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Invitation Quinceanera Espanol
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6113

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.