3.4. Printing a Date or Time in a Specified Format
Problem
You need to print out a date or time formatted in a particular way.
Solution
Use date( ) or strftime( ):
print strftime('%c');
print date('m/d/Y');
Tue Jul 30 11:31:08 2002
07/30/2002Discussion
Both date( )
and strftime( ) are
flexible functions that can produce a formatted time string with a
variety of components. The formatting characters for these functions
are listed in Table 3-3. The Windows column indicates whether the
formatting character is supported by strftime( )
on Windows systems.
Table 3-3. strftime( ) and date( ) format characters
|
Type |
strftime( ) |
date( ) |
Description |
Range |
Windows |
|---|---|---|---|---|---|
|
Hour |
|
|
Hour, numeric, 24-hour clock |
00-23 |
Yes |
|
Hour |
|
|
Hour, numeric, 12-hour clock |
01-12 |
Yes |
|
Hour |
|
Hour, numeric, 24-hour clock, leading zero as space |
0-23 |
No | |
|
Hour |
|
Hour, numeric, 12-hour clock, leading zero as space |
1-12 |
No | |
|
Hour |
|
|
AM or PM designation for current locale |
Yes | |
|
Hour |
|
|
am/pm designation for current locale |
No | |
|
Hour |
|
Hour, numeric, 24-hour clock, leading zero trimmed |
0-23 |
No | |
|
Hour |
|
Hour, numeric, 12-hour clock, leading zero trimmed |
0-1 |
No | |
|
Minute |
|
|
Minute, numeric |
00-59 |
Yes |
|
Second |
|
|
Second, numeric |
00-61[a] |
Yes |
|
Day |
|
|
Day of the month, numeric |
01-31 |
Yes |
|
Day |
|
Day of the month, numeric, leading zero as space |
1-31 |
No | |
|
Day |
|
|
Day of the year, numeric |
001-366 for |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access