Python Date and Time

Python programs can handle dates and times in many ways, and converting date formats is a common feature.

Python provides time and calendar modules that can be used to format dates and times.

Time intervals are floating-point numbers in seconds.

Each timestamp is expressed as the amount of time that has passed since midnight (epoch) on January 1, 1970.

The time module in Python has many functions for converting common date formats. For example, the function time.time() is used to get the current timestamp, as in the following example:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import time # Import the time module ticks = time.time() print "Current timestamp is:", ticks

The output of the above example is:

当前时间戳为: 1459994552.51

The timestamp unit is most suitable for date arithmetic. However, dates before 1970 cannot be represented this way. Dates too far in the future also won't work, as UNIX and Windows only support up to 2038.



What is a time tuple?

Many Python functions process time as a tuple of 9 groups of numbers:

No.FieldValue
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 the week0 to 6 (0 is Monday)
7Day of the year1 to 366 (Julian calendar)
8Daylight saving time-1, 0, 1; -1 is a flag to determine whether it is daylight saving time

The above is the struct_time tuple. This structure has the following attributes:

No.AttributeValue
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 calendar)
8tm_isdst-1, 0, 1; -1 is a flag to determine whether it is daylight saving time


Get current time

To convert a timestamp expressed as a floating-point number into a time tuple, simply pass the floating-point number to a function such as localtime.

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import time localtime = time.localtime(time.time()) print "Local time is :", localtime

The output of the above example is:

本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)


Get formatted time

You can choose various formats according to your needs, but the simplest function for obtaining a readable time format is asctime():

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import time localtime = time.asctime( time.localtime(time.time()) ) print "Local time is :", localtime

The output of the above example is:

本地时间为 : Thu Apr  7 10:05:21 2016

Format date

We can use the strftime method of the time module to format dates:

time.strftime(format[, t])

Example demonstration:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import time # Format as 2016-03-20 11:45:39 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # Format as Sat Mar 28 22:24:24 2016 print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) # Convert format string to timestamp a = "Sat Mar 28 22:24:24 2016" print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

The output of the above example is:

2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0

Python date and time formatting symbols:

  • %y Two-digit year representation (00-99)
  • %Y Four-digit year representation (000-9999)
  • %m Month (01-12)
  • %d Day of the month (0-31)
  • %H Hour in 24-hour format (0-23)
  • %I Hour in 12-hour format (01-12)
  • %M Minute (00-59)
  • %S Second (00-59)
  • %a Locale's abbreviated weekday name
  • %A Locale's full weekday name
  • %b Locale's abbreviated month name
  • %B Locale's full month name
  • %c Locale's appropriate date and time representation
  • %j Day of the year (001-366)
  • %p Locale's equivalent of A.M. or P.M.
  • %U Week number of the year (00-53), Sunday as the first day of the week
  • %w Weekday (0-6), Sunday as the first day of the week
  • %W Week number of the year (00-53), Monday as the first day of the week
  • %x Locale's appropriate date representation
  • %X Locale's appropriate time representation
  • %Z Name of the current time zone
  • %% The % character itself

Get calendar for a month

The Calendar module has a wide range of methods for handling yearly and monthly calendars, for example, printing the calendar of a month:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import calendar cal = calendar.month(2016, 1) print "The following outputs the calendar for January 2016:" print cal

The output of the above example is:

以下输出2016年1月份的日历:
    January 2016
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31


Time Module

The Time module contains the following built-in functions, both for time processing and for converting time formats:

No.Function and description
1time.altzone
Returns the offset in seconds of the daylight saving time (DST) region west of Greenwich. If the region is east of Greenwich, a negative value is returned (such as Western Europe, including the UK). Only available for regions where daylight saving time is enabled.
2time.asctime([tupletime])
Accepts a time tuple and returns a readable 24-character string in the form "Tue Dec 11 18:07:14 2008" (December 11, 2008, Tuesday, 18:07:14).
3time.clock( )
Returns the current CPU time as a floating-point number of seconds. Used to measure the elapsed time of different programs, more useful than time.time().
4time.ctime([secs])
It is equivalent to asctime(localtime(secs)); when no argument is given, it is equivalent to asctime().
5time.gmtime([secs])
Accepts a timestamp (floating-point seconds elapsed since the epoch 1970) and returns a time tuple t in Greenwich Mean Time (GMT). Note: t.tm_isdst is always 0.
6time.localtime([secs])
Accepts a timestamp (floating-point seconds elapsed since the epoch 1970) and returns a time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether daylight saving time is in effect locally at that time).
7time.mktime(tupletime)
Accepts a time tuple and returns a timestamp (floating-point seconds elapsed since the epoch 1970).
8time.sleep(secs)
Delays the execution of the calling thread, secs is in seconds.
9time.strftime(fmt[,tupletime])
Accepts a time tuple and returns local time as a readable string, the format is determined by fmt.
10time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
Parses a time string into a time tuple according to the format fmt.
11time.time( )
Returns the timestamp of the current time (floating-point seconds elapsed since the epoch 1970).
12time.tzset()
Reinitializes time-related settings based on the environment variable TZ.

The Time module contains the following 2 very important attributes:

No.Attribute and description
1time.timezone
The attribute time.timezone is the offset in seconds of the local time zone (without daylight saving time) from Greenwich (>0, Americas; <=0, most of Europe, Asia, Africa).
2time.tzname
The attribute time.tzname contains a pair of strings that differ depending on the situation, namely the local time zone name with daylight saving time and that without it.


Calendar Module

The functions in this module are all calendar-related, for example, printing the character-based monthly calendar of a month.

Monday is the default first day of the week, and Sunday is the default last day. To change the setting, you need to call the calendar.setfirstweekday() function. The module contains the following built-in functions:

No.Function and description
1calendar.calendar(year,w=2,l=1,c=6)
Returns a multi-line string format for the year (year) calendar, with 3 months per row, separated by a distance of c. The daily width interval is w characters. The length of each row is 21* W+18+2* C. l is the number of lines per week.
2calendar.firstweekday( )
Returns the setting for the current starting day of the week. By default, when the calendar module is first loaded, it returns 0, which is Monday.
3calendar.isleap(year)

Returns True if it is a leap year, otherwise returns False.

>>> import calendar
>>> print(calendar.isleap(2000))
True
>>> print(calendar.isleap(1900))
False
4calendar.leapdays(y1,y2)
Returns the total number of leap years between years Y1 and Y2.
5calendar.month(year,month,w=2,l=1)
Return a multi-line string calendar for year year and month month, with a two-line title and one line per week. The daily width interval is w characters. The length of each line is 7*w+6. l is the number of lines for each week.
6calendar.monthcalendar(year,month)
Return a single-layer nested list of integers. Each sublist contains integers representing a week. Dates outside year year and month month are set to 0; days within range are represented by the day of that month, starting from 1.
7calendar.monthrange(year,month)
Return two integers. The first is the weekday date code of that month, and the second is the date code of that month. Days range from 0 (Monday) to 6 (Sunday); months from 1 to 12.
8calendar.prcal(year,w=2,l=1,c=6)
Equivalent toprint calendar.calendar(year,w=2,l=1,c=6)。
9calendar.prmonth(year,month,w=2,l=1)
Equivalent toprint calendar.month(year,month,w=2,l=1) 。
10calendar.setfirstweekday(weekday)
Set the starting date code for each week. 0 (Monday) to 6 (Sunday).
11calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time tuple and returns the timestamp of that moment (floating-point seconds elapsed since the 1970 epoch).
12calendar.weekday(year,month,day)
Return the date code for the given date. 0 (Monday) to 6 (Sunday). Months are 1 (January) to 12 (December).


Other related modules and functions

In Python, other modules for handling dates and times include:

Other extensions