Python method to get the current time

  • 2020-04-02 13:19:33
  • OfStack

I sometimes write programs that use the current time, and I just want to use python to get the current time, and it's not too hard, but I always forget, I throw it away,
In order to better remember, I have written down the method of getting the current time, if you think it is useful for you, you can save it.

To get time related information, you need to use the python time module, which has a lot of very useful functions, you can go to the official
To get the current time, you need to get a timestamp of the current time, which looks like the time between 1970 and the present time.

You can try the following method to get the timestamp of the current time:
The import time
The print time. Time ()
The output result is:
1279578704.6725271

But this is a series of Numbers is not the result we want, we can use the time module format method to deal with:
Time. A localtime (time. Time ())
Use the time.localtime() method to format the timestamp as the localtime.
The output result is:
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 likely to be formatted as the time we want.
Time. Strftime (' % Y - % m - % d ', time. The localtime (time. Time ()))

Finally, we use the method time.strftime() to format the previous string of information into what we want. Now the result is:
2010-07-19

Strftime has many parameters that allow you to output what you want more freely:
The following is the parameter of time.strftime:
The strftime (format [, tuple]) - > The string
Outputs the specified struct_time(the default is the current time) according to the specified formatted string
Time and date formatting symbol in python:
The two-digit year of %y is (00-99).
The year of %Y with four digits (000-9999)
Month (01-12)
%d day of the month (0-31)
%H 24-hour hours (0-23)
%I 12 hours (01-12)
%M minutes (00=59)
%S seconds (00-59)

%a locally simplified week name
%A local full week name
%b local simplified month name
%B local full month name
%c local corresponding date and time representations
%j one day in the year (001-366)
Local A.M. or P.M. equivalent of %p
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
The number of weeks in a year (00-53) Monday is the beginning of the week
%x is represented locally by the corresponding date
%X local corresponding time representation
%Z the name of the current time zone
The %% % sign itself

You can try it yourself if you are interested.


Related articles: