Home  >  Article  >  Backend Development  >  Understanding the dateutil module in Python (with examples)

Understanding the dateutil module in Python (with examples)

不言
不言forward
2018-12-04 17:30:466192browse

This article brings you the understanding of the dateutil module in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

I have recently come into contact with the Python project in the project team and found that all time formats use iso8601. My colleagues euphemistically said it was for the internationalization of the project (in fact, the number of users is at most a few hundred people) Well, they are all concentrated within the company, where does the internationalization come from, hahahaha!). So I decided to do an in-depth study of the time format and discovered the dateutil module in python.

DATETIME to ISO8601 format, just use the isoformat() method to convert it

now_time = datetime.now().isoformat()

The output is

2018-12-04T08:44:35.792445
  • Parse DATETIME from a string Format (without dateutil module)

now_date_str = datetime.now().isoformat().split('.')[0]
my_format = '%Y-%m-%dT%H:%M:%S'
print(datetime.strptime(now_date_str, my_format))

This is the most commonly used method in python to convert a string into time format. The output result is

2018-12-04 08:44:35
  • Use dateutil to parse strings

from dateutil.parser import parse
timestamp = parse(now_date_str, fuzzy=True)
print(timestamp)

The output results are the same as above, but the fuzzy in this parse method is amazing and can fuzzy match the time format. If you are interested, you can check out the source code!

  • Calculate the time difference

today = date.today()
my_birthday = date(year=1992, month=3, day=17)
print('我已经出生' + str((today - my_birthday).days) + '天')

I can directly calculate how many days since I was born, and the output is

我已经出生9758天

But if I want What happens when you calculate how old I am, that is, how many years since I was born?

Traceback (most recent call last):
2018-12-04 08:57:08
  File "F:/pythonProject/testcode/testDate.py", line 27, in <module>
    print((today-my_birthday).years)
2018-12-04 08:57:08
AttributeError: 'datetime.timedelta' object has no attribute 'years'

Unfortunately, an error was reported because there is no method to obtain the year and month in timedelta, so we continue to use the dateutil module

from dateutil.relativedelta import relativedelta
diff = relativedelta(today, my_birthday)

We can find through the output that we can get the middle of the two dates Differences in years, months and days

relativedelta(years=+26, months=+8, days=+17)
print(diff.years)
print(diff.months)
print(diff.days)
26
8
17
  • Get a list of dates. If you need to get the dates of Tuesdays for five consecutive weeks, it can be easily achieved through dateutil

from dateutil.rrule import rrule, WEEKLY
pp(list(rrule(WEEKLY, count=10, dtstart=next_tuesday)))

The output is

[datetime.datetime(2018, 12, 4, 8, 59, 6),
 datetime.datetime(2018, 12, 11, 8, 59, 6),
 datetime.datetime(2018, 12, 18, 8, 59, 6),
 datetime.datetime(2018, 12, 25, 8, 59, 6),
 datetime.datetime(2019, 1, 1, 8, 59, 6),
 datetime.datetime(2019, 1, 8, 8, 59, 6),
 datetime.datetime(2019, 1, 15, 8, 59, 6),
 datetime.datetime(2019, 1, 22, 8, 59, 6),
 datetime.datetime(2019, 1, 29, 8, 59, 6),
 datetime.datetime(2019, 2, 5, 8, 59, 6)]

Note: dtstart must be in time format

The above is the detailed content of Understanding the dateutil module in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete