Python notes: time library and datetime library

0 Preface

The story also originated from work:

  • In a task in the first two days, you need to get the time period from the current time point to a week ago. The task itself is actually quite simple, but the pitfall is that after we successfully tested it locally, we pushed it online, and the result was online. The current time obtained in the service on the Internet is not calibrated, and then the appearance setting time of the device is obtained, and then the cup is served. . .

In view of this pit, in fact, the method to deal with is relatively simple:

  • We just need to take the world time first and then convert it to Beijing time.

However, it also exposed my unfamiliarity with the datetime library. Therefore, here is a small hydrology to sort out the following two time-related libraries:

  1. time library
  2. datetime library

In order to avoid becoming a document translation like the previous article, here, we first briefly introduce some of the commonly used functions, and then use two actual cases to explain.

1. Introduction to basic functions

1. time library

Here, let's take a look at some commonly used functions in the time library.

  1. time.time()
    • Get the current machine time and return it as a float decimal in seconds.
  2. time.sleep(secs)
    • Pause the current thread, wait for secsseconds, and restart the thread to continue running the program.
  3. time.asctime([t])
    • Use the default string expression to display the time expressed by t, if t is empty, the default value is the current time;
  4. time.localtime([secs])
    • Convert a float type of time to a struct_timetype of time and return. If secs is empty, the default value is the current time, that is time.time(), the result.
  5. time.strftime(format, [t])
    • Convert the time t ( tupleor struct_timetype) to string type and agree, where format is a custom display format, such as:, "%Y-%m-%d %H:%M:%S %a %Z(%z)"displayed as:, 2021-01-28 13:44:07 Thu CST(+0800)for more parameter definitions, please refer to the official website document.

2. datetime library

Similarly, we give some commonly used methods in the datetime library as follows:

  1. datetime.datetime.now()
    • Get the current time, datetime data format
  2. datetime.datetime.utcnow()
    • Get UTC time, datetime data format
  3. datetime.datetime.timedelta()
    • Get time difference, datetime data format
  4. datetime.strftime()
    • Class method, convert the datetime class to string for printing
  5. datetime.timestamp()
    • Class method, convert the datetime class to float type timestamp

2. Case study

1. Retry implementation

Here, we give a simple decorator to realize the automatic retry process when the function fails.

def retry(retry_time=3, fix_time=5):
    def decorator(func):
        def fn(*args, **kwargs):
            for i in range(retry_time):
                try:
                    return func(*args, **kwargs)
                except:
                    print(f"function {func.__name__ } failed {i+1} times.")
                    time.sleep(fix_time)
            raise Exception(f"function {func.__name__ } still failed after {retry_time} times retry.")
        return fn
    return decorator

2. Perform time-consuming calculations on any function

Similarly, we can also use decorators to return the execution time of any function.

def count_time(func):
    def fn(*args, **kwargs):
        t1 = time.time()
        res = func(*args, **kwargs)
        t2 = time.time()
        print(f"function {func.__name__} cost time: {t2-t1:.2} secs")
        return res
    return fn

3. Get Beijing time

We give a general method for obtaining Beijing time as follows:

def get_time(time_format="%Y-%m-%d %H:%M:%S"):
    peiking_time = datetime.timezone(
        datetime.timedelta(hours=8),
        name='PeiKing Time',
    )
    utc_time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    return utc_time.strftime(time_format)

In particular, if there is a shift in the time that needs to be obtained, we only need to adjust the code slightly:

def get_time(delta=0, time_format="%Y-%m-%d %H:%M:%S"):
    peiking_time = datetime.timezone(
        datetime.timedelta(hours=8),
        name='PeiKing Time',
    )
    utc_time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    t = utc_time.astimezone(peiking_time) + datetime.timedelta(delta)
    return t.strftime(time_format)

3. Reference link

  1. https://docs.python.org/3/library/time.html
  2. https://docs.python.org/3/library/datetime.html

Guess you like

Origin blog.csdn.net/codename_cys/article/details/113531652