web123456

Python Advanced (33) Python obtains and outputs the current date and time

If you obtain time-related information, you must use itpython timeModule,python timeThere are many very useful functions in the module, you can go to the official documentation to learn about it. The timestamp is a time between 1970 and now.

You can try the following method to get the time stamp of the current time:

import time
print time.time()

The output result is: 1357723206.31

But this is a series of numbers that are not the result we want. We can use the time module formatting time method to handle it:

time.localtime(time.time())

Using the () method, the function is to format the time stamp to the local time.

The output result is: time.struct_time(tm_year=2010, tm_mon=7, tm_mday=19, tm_hour=22, tm_min=33, tm_sec=39, tm_wday=0, tm_yday=200, tm_isdst=0)

Now it looks more promising to format the time we want.

time.strftime('%Y-%m-%d',time.localtime(time.time()))

Finally, using the () method, format the whole string of information just now into what we want. The result is:
2013-01-09

Output date and time:

time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

There are many parameters in it that allow you to output what you want more casually:

The following parameters:

strftime(format[, tuple]) -> string

The specified struct_time (default is the current time) is output according to the specified format string.

Time and date formatting symbols in python:

  • %y Double digit year representation (00-99)
  • %Y Four-digit year representation (000-9999)
  • %m Month (01-12)
  • %d One day in the month (0-31)
  • %H 24-hour hours (0-23)
  • %I 12-hour hours (01-12)
  • %M Minutes (00=59)
  • %S seconds (00-59)
  • %a Local simplified week name
  • %A Local full week name
  • %b Locally simplified month name
  • %B Local full month name
  • %c Local corresponding date and time representation
  • %j One day in the year (001-366)
  • %p local .or. equivalence
  • %U The number of weeks of the year (00-53) Sunday is the beginning of the week
  • %w Week (0-6), Sunday is the beginning of the week
  • %W The number of weeks of the year (00-53) Monday is the beginning of the week
  • %x local corresponding date
  • %X local corresponding time representation
  • %Z The name of the current time zone
  • %% % % number itself