Time, strftime and strptime in Python

The most common

time.time() returns a floating point number in seconds. But the type that strfTime handles is time.struct_time, which is actually a tuple. Both strpTime and localTime will return this type.

>>> import time
>>> t = time.time()
>>> t
1202872416.4920001
>>> type(t)
<type 'float'>
>>> t = time.localtime()
>>> t
(2008, 2, 13, 10, 56, 44, 2, 44, 0)
>>> type(t)
<type 'time.struct_time'>
>>> time.strftime('%Y-%m-%d', t)
'2008-02-13'
>>> time.strptime('2008-02-14', '%Y-%m-%d')
(2008, 2, 14, 0, 0, 0, 3, 45, -1)

1, strftime usage

strftime can be used to get the current time, you can format the time as a string, and so on, which is pretty handy. However, it should be noted that the acquired time is the time of the server, and pay attention to the time zone issues, such as GAE lying that the time is the 0 time zone of GMT, which needs to be converted by itself.

Strftime ()

strftime ()
we can use the strftime () function to format the time in the desired format

#!/usr/bin/python
import time

t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
t = time.mktime(t)
print time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t))

#输出:Feb 17 2009 09:03:38

2. Strptime

The

Python time strptime() function parses a time string into a time tuple according to the specified format.
python time date formatting symbol:

  • %y two-digit years are (00-99)
  • %y four-digit years are (000-9999)
  • %m months (01-12)
  • %d months (0-31)
  • %H 24 H hours (0-23)
  • 0

  • 1% I 12-hour hours (01-12)
  • 3% m minutes (00=59)

    4

  • 5% S Second (00-59)
  • %a local simplified name of the week
  • %a local simplified name of the week
  • %b local simplified name of the month
  • %b local complete name of the month
  • %c local corresponding date and time expression
  • 0

  • 1% a day (001-366)
  • 2
  • 3% p local a.m. The number of weeks of the year (00-53) Sunday is the beginning of the week
  • %w (0-6), Sunday is the beginning of the week
  • %w (00-53) Monday is the beginning of the week
  • %x local corresponding date is
  • %x local corresponding time is
  • 0

  • 1 %Z current time zone name
  • 2

  • 3 %% %% %U number itself
  • 4

5

instance:

#!/usr/bin/python
import time

struct_time = time.strptime("30 Nov 00", "%d %b %y")
print "returned tuple: %s " % struct_time

#输出:returned tuple: (2000, 11, 30, 0, 0, 0, 3, 335, -1)

Read More: