Python commonly used built-in module datetime

Python study notes, special records, share with you, I hope it will be helpful to everyone.

datetime is Python's standard library for handling dates and times.

Get the current date and time

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

from datetime import datetime

# 获取当前datetime
now = datetime.now()
print now
print type(now)

operation result:

2019-07-15 18:50:19.042200
<type 'datetime.datetime'>

Process finished with exit code 0

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

If only import datetime is imported, the full name datetime.datetime must be quoted.

datetime.now() returns the current date and time, and its type is datetime.

Get the specified date and time

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

from datetime import datetime

# 用指定日期时间创建datetime
dt = datetime(2015, 4, 19, 12, 20)
print dt

operation result:

2015-04-19 12:20:00

Process finished with exit code 0

Convert datetime to timestamp

In computers, time is actually expressed in numbers. We call the time of 00:00:00 UTC+00:00 on January 1, 1970 as epoch time, which is recorded as 0 (timestamp before 1970 is a negative number), and the current time is the number of seconds relative to epoch time , Called timestamp.

You can think of:

timestamp = 0 = 1970-1-1 00:00:00 UTC+0:00

The corresponding Beijing time is:

timestamp = 0 = 1970-1-1 08:00:00 UTC+8:00

It can be seen that the value of timestamp has nothing to do with the time zone, because once the timestamp is determined, the UTC time is determined, and the time converted to any time zone is also completely determined. This is why the current time stored in the computer is expressed in timestamp, because all over the world The timestamp of the computer at any moment is exactly the same (assuming that the time is calibrated).

Converting a datetime type to timestamp only needs to simply call the timestamp() method:

# 用指定日期时间创建datetime
dt = datetime(2015, 4, 19, 12, 20)
# 把datetime转换为timestamp
print dt.timestamp()

operation result:

1429417200.0

Process finished with exit code 0

Note that Python's timestamp is a floating point number. If there is a decimal place, the decimal place represents the number of milliseconds.

The timestamp of some programming languages ​​(such as Java and JavaScript) uses an integer to represent the number of milliseconds. In this case, you only need to divide the timestamp by 1000 to get the floating point representation of Python.

timestamp converted to datetime

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

from datetime import datetime
t = 1429417200.0
print datetime.fromtimestamp(t)

operation result:

2015-04-19 12:20:00

Process finished with exit code 0

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

The local time refers to the time zone set by the current operating system. For example, the Beijing time zone is East 8, the local time:

2015-04-19 12:20:00

It is actually the time in the UTC+8:00 time zone:

2015-04-19 12:20:00 UTC+8:00

At this moment, there is a difference of 8 hours between Greenwich Mean Time and Beijing Time, that is, the time in the UTC+0:00 time zone should be:

2015-04-19 04:20:00 UTC+0:00

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

from datetime import datetime
t = 1429417200.0
print datetime.fromtimestamp(t)  # 本地时间
print datetime.utcfromtimestamp(t) # UTC时间

operation result:

2015-04-19 12:20:00
2015-04-19 04:20:00

Process finished with exit code 0

str is converted to datetime

In many cases, the date and time entered by the user are strings. To process the date and time, you must first convert str to datetime. The conversion method is implemented by datetime.strptime(), which requires a date and time formatted string:

from datetime import datetime
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
print cday

operation result:

2015-06-01 18:19:59

Process finished with exit code 0

The string '%Y-%m-%d %H:%M:%S'specifies the format of the date and time part. For detailed instructions, please refer to the Python documentation .

Note that the converted datetime has no time zone information.

convert datetime to str

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

from datetime import datetime
now = datetime.now()
print now.strftime('%a, %b %d %H:%M')

operation result:

Mon, May 05 16:28

Process finished with exit code 0

datetime addition and subtraction

Adding and subtracting the date and time is actually calculating the datetime backward or forward to get a new datetime. You can use the + and-operators directly for addition and subtraction, but you need to import the timedelta class:

from datetime import datetime, timedelta
now = datetime.now()
print now
print now + timedelta(hours=10)
print now - timedelta(days=1)
print now + timedelta(days=2, hours=12)

operation result:

datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)

Process finished with exit code 0

It can be seen that using timedelta you can easily calculate the moments in the first few days and the next few days.

Convert local time to UTC time

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

A datetime type has a time zone attribute tzinfo, but the default is None, so it is impossible to distinguish which time zone the datetime is, unless a time zone is forcibly set for datetime:

from datetime import datetime, timedelta, timezone
tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00
now = datetime.now()
print now
dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00
print dt

operation result:

datetime.datetime(2015, 5, 18, 17, 2, 10, 871012)
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))

Process finished with exit code 0

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

Time zone conversion

We can first get the current UTC time through utcnow(), and then convert it to the time in any time zone:

# 拿到UTC时间,并强制设置时区为UTC+0:00:
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print utc_dt
# astimezone()将转换时区为北京时间:
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print bj_dt
# astimezone()将转换时区为东京时间:
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
print tokyo_dt
# astimezone()将bj_dt转换时区为东京时间:
tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))
print tokyo_dt2

operation result:

2015-05-18 09:05:12.377316+00:00
2015-05-18 17:05:12.377316+08:00
2015-05-18 18:05:12.377316+09:00
2015-05-18 18:05:12.377316+09:00

Process finished with exit code 0

The key to time zone conversion is to know the correct time zone when you get a datetime, and then force the time zone to be set as the reference time.

Using datetime with time zone, you can switch to any time zone through the astimezone() method.

Note: It is not necessary to switch from UTC+0:00 time zone to other time zones. Any datetime with time zone can be converted correctly, such as the conversion from bj_dt to tokyo_dt mentioned above.

Guess you like

Origin blog.csdn.net/qq_36478920/article/details/103085670