[python] basic knowledge consolidation

Posted by jvrothjr on Mon, 03 Jan 2022 06:53:28 +0100


datetime Library

Get current date and time

Gets the specified date and time

datetime to timestamp

timestamp to datetime

str to datetime

datetime to str

datetime addition and subtraction

Convert local time to UTC time

Time zone conversion

collections Library







datetime Library

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

Get current date and time

from datetime import datetime
now = datetime.now()


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

If you import only {import datetime, you must reference the full name} datetime datetime.

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

Gets the specified date and time

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

from datetime import datetime
dt = datetime(2015,4,19,12,20)

datetime to timestamp

Let's first understand what is timestamp?

The time of 00:00:00 UTC+00:00 time zone on January 1, 1970 is called epoch time (as for why baidu is recommended)

We define the current time as the number of seconds relative to epoch time, which is called timestamp

Note that Python's timestamp is a floating point number, and integer bits represent seconds.

>>> from datetime import datetime
>>> dt = datetime(2015, 4, 19, 12, 20) # Creates a datetime with the specified date time
>>> dt.timestamp() # Convert datetime to timestamp

timestamp to datetime

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

1) timestamp and local time are converted

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00

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

>>> print(datetime.utcfromtimestamp(t)) # UTC time
2015-04-19 04:20:00

str to datetime

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

datetime to str

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

datetime addition and subtraction

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

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)

Convert local time to UTC time

Knowledge points:

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

We can know that a datetime type has a time zone attribute tzinfo, but the default is None, so we can't distinguish which time zone this datetime is, unless we force a time zone for datetime:

>>> from datetime import datetime, timedelta, timezone
>>> tz_utc_8 = timezone(timedelta(hours=8)) # Create time zone UTC+8:00
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012)
>>> dt = now.replace(tzinfo=tz_utc_8) # Force to UTC+8:00
>>> dt
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))

Time zone conversion

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


# Get the UTC time and force the time zone to UTC+0:00:
>>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
>>> print(utc_dt)
2015-05-18 09:05:12.377316+00:00
# astimezone() converts the time zone to Beijing time:
>>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
>>> print(bj_dt)
2015-05-18 17:05:12.377316+08:00
# astimezone() converts the time zone to Tokyo time:
>>> tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
>>> print(tokyo_dt)
2015-05-18 18:05:12.377316+09:00
# astimezone() will bj_dt convert time zone to Tokyo time:
>>> tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))
>>> print(tokyo_dt2)
2015-05-18 18:05:12.377316+09:00

astimezone() method



  • tz - timezone information which should be changed.

    tz - time zone information that should be changed.

  • eg:

  • astimezone(timezone(timedelta(hours=8)))

The timedelta class represents the time difference

td = timedelta(days=1, hours=6)


collections Library

collections is a collection module built in Python, which provides many useful collection classes.


Tuple can represent an invariant set, and tuple is used to represent a coordinate (I personally think it's a bit like a simple version of class)


from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
#output: 1


from collections import namedtuple
Student = namedtuple("_Student","name,age sex like")
stud1 = Student("Zhang San",15,"male","Play basketball")


When using list to store data, it is very fast to access elements by index, but it is very slow to insert and delete elements, because list is linear storage. When the amount of data is large, the insertion and deletion efficiency is very low.

deque is a bidirectional list for efficient insertion and deletion. It is suitable for queues and stacks:

from collections import deque
q = deque(['a', 'b', 'c'])



When using dict, if the referenced Key does not exist, KeyError will be thrown.

If you want to return a default value when the key does not exist, you can use defaultdict:

from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
dd['key1'] # key1 exists
dd['key2'] # key2 does not exist. The default value is returned



Because dict is out of order, you can use OrderedDict to maintain the order of keys

from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
od # The Key of OrderedDict is ordered




ChainMap can string a group of dicts and form a logical dict. ChainMap itself is also a dict, but when searching, it will find the internal dict in order

from collections import ChainMap
values = ChainMap()
values['x'] = 3
values = values.new_child()
values['x'] = 2

values = values.new_child()

values['x'] = 1


Counter is a simple counter. For example, count the number of characters:

from collections import Counter
c = Counter()
for ch in 'programming':
     c[ch] = c[ch] + 1






Topics: Python Back-end