RPA - Processing time using Python's datetime Library

Posted by graham23s on Sat, 23 Nov 2019 10:10:41 +0100

During RPA process automation, some methods of the datetime library can be called to handle time-related operations.
datetime is the standard library for Python processing dates and times.

1. Get the current date and time

Let's first see how to get the current date and time:

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now)
2019-11-23 11:12:32.715604
>>> print(type(now))
<class 'datetime.datetime'>

Notice that datetime is a module and that the datetime module also contains a datetime class, which is imported from datetime import datetime.

If only import datetime is imported, the full name datetime.datetime must be referenced.
datetime.now() returns the current date and time, which is of type datetime.

2. Get the specified date and time

To specify a date and time, we construct a datetime directly with parameters:

>>> from datetime import datetime
>>> time = datetime(2008,8,8,8,8) # Create datetime with specified date and time
>>> print(time)
2008-08-08 08:08:00

3. datetime to timestamp

In computers, time is actually represented by numbers.We refer to the time zone of 100:00:00 UTC+00:00 on January 1, 1970 as epoch time, which is recorded as 0 (negative time stamp before 1970). The current time is the number of seconds relative to epoch time, called timestamp.

You can think:
timestamp = 0 = 1970-1-1 00:00:00 UTC+0:00

The corresponding time in Beijing is:
timestamp = 0 = 1970-1-1 08:00:00 UTC+8:00

It is clear that the value of timestamp has nothing to do with time zones, because once a timestamp is determined, its UTC time is determined, and the time it is converted to any time zone is also completely determined, which is why the current time stored by the computer is expressed in timestamp, because computers all over the world are exactly the same timestamp at any time (assuming that the time has been calibrated).

Converting a datetime type to timestamp simply calls the timestamp() method:

>>> from datetime import datetime
>>> time = datetime(2019,11,23,11,25)
>>> time.timestamp()
1574479500.0

Note that Python's timestamp is a floating point number.If there are decimal places, decimal places represent milliseconds.

4. Convert timestamp to datetime

To convert timestamp to datetime, use the fromtimestamp() method provided by datetime:

>>> from datetime import datetime
>>> time = 1574479500.0
>>> print(datetime.fromtimestamp(time))
2019-11-23 11:25:00

Notice that timestamp is a floating point number, it has no concept of time zone, and datetime is time zone.The above conversion is done at timestamp and local time.

Local time refers to the time zone set by the current operating system.For example, if the Beijing time zone is East 8, the local time is 2019-11-23 11:25:00

It's actually UTC+8:00 time zone: 2019-11-23 11:25:00 UTC+8:00

At this point, Greenwich Mean Time is 8 hours behind Beijing Time, which means UTC+0:00 time zone should be:

2019-11-23 03:25:00 UTC+0:00

Timstamp can also be converted directly to UTC standard time zone time:

>>> from datetime import datetime
>>> time = 1574479500.0
>>> print(datetime.fromtimestamp(time))
2019-11-23 11:25:00
>>> print(datetime.utcfromtimestamp(time)) # UTC Time
2019-11-23 03:25:00

5. Convert str to datetime

Many times, the date and time entered by the user is a string. To process the date and time, you must first convert str to datetime.The conversion method is implemented through datetime.strptime(), which requires a formatted string of date and time:

>>> from datetime import datetime
>>> today = datetime.strptime('2019-11-23 11:34:49','%Y-%m-%d %H:%M:%S')
>>> print(today)
2019-11-23 11:34:49
>>>

The string'%Y-%m-%d%H:%M:%S'specifies the format of the date and time part. Note that the converted datetime has no zone information.

6. datetime to str

If you already have a datetime object and want to format it as a string to display to the user, you need to convert it to str by strftime(), which also requires a formatted string for date and time:

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now.strftime('%a, %b %d %H:%M'))
Sat, Nov 23 14:45

7. datetime Addition and Subtraction

Adding or subtracting dates and times is essentially calculating datetime backward or forward to get a new datetime.Addition and subtraction can use the + and - operators directly, but you need to import the timedelta class:

>>> from datetime import datetime,timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2019, 11, 23, 14, 49, 49, 739236)
>>> now + timedelta(hours = 5)
datetime.datetime(2019, 11, 23, 19, 49, 49, 739236)
>>> now - timedelta(days = 1)
datetime.datetime(2019, 11, 22, 14, 49, 49, 739236)
>>> now - timedelta(days = 3,hours = 3)
datetime.datetime(2019, 11, 20, 11, 49, 49, 739236)

Visibly, using timedelta you can easily calculate the first few days and the next few days.

8. Convert local time to UTC time

Local time refers to the time zone set by the system, for example, Beijing time is UTC+8:00 time zone, while UTC time refers to UTC+0:00 time zone.

A datetime type has a time zone attribute tzinfo, but defaults to None, so it is not possible to tell which time zone this datetime is unless a time zone is forcibly set for datetime:

>>> from datetime import datetime,timedelta,timezone
>>> time_utc = timezone(timedelta(hours=8)) # Create time zone UTC+8:00
>>> now = datetime.now()
>>> now
datetime.datetime(2019, 11, 23, 14, 55, 5, 901745)
>>> now_utc = now.replace(tzinfo=time_utc) # Forced to UTC+8:00
>>> now_utc
datetime.datetime(2019, 11, 23, 14, 55, 5, 901745, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))

If the system time zone happens to be UTC+8:00, the above code is correct, otherwise you cannot force it to be UTC+8:00.

9. Time Zone Conversion

You can get the current UTC time by utcnow(), then convert it to any time zone:

>>> utc_time = datetime.utcnow().replace(tzinfo=timezone.utc) # Get UTC time and force the time zone to be UTC+0:00
>>> print(utc_time)
2019-11-23 07:05:25.865221+00:00
>>>
>>> bj_time = utc_time.astimezone(timezone(timedelta(hours=9))) #astimezone() will convert the time zone to Tokyo Time
>>> print(bj_time)
2019-11-23 16:05:25.865221+09:00
>>>
>>> dj_time = utc_time.astimezone(timezone(timedelta(hours=9))) #Convert Time Zone to Tokyo Time
>>> print(dj_time)
2019-11-23 16:05:25.865221+09:00
>>>
>>> dj_time2 = bj_time.astimezone(timezone(timedelta(hours=9))) #Convert Beijing Time to Tokyo Time
>>> print(dj_time2)
2019-11-23 16:05:25.865221+09:00

The key to time zone conversion is to know the correct time zone when you get a datetime, then force the time zone to be set as the base time.
Using datetime with a time zone, you can convert to any time zone using the astimezone() method.

Note: It is not necessary to convert from UTC+0:00 time zone to other time zones. Any datetime with time zone can be correctly converted, such as the bj_time to dj_time2 conversion described above.

Summary

The time represented by datetime requires time zone information to determine a specific time, otherwise it can only be considered local time.
If you want to store datetime, the best way is to convert it to timestamp and store it again, because the value of timestamp is completely independent of time zone.

Free download trial: https://support.i-search.com.cn/

Topics: Python Attribute