In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what is the use of DateTime library Pendulum in Python. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
1. Directly replace datetime
It is not uncommon to use third-party libraries such as pytz to solve problems that Python datetime is not good at. However, we still need to import the datetime module and use it as essential, because we need to use it to instantiate the datetime object.
Let me show you why Pendulum is a substitute. First, we need to install it using pip.
Pip install pendulum
The name of the library is a bit long, so I recommend importing it with an alias
Import pendulum as pdl
Although pd is a short acronym, I will keep it for Pandas. I don't want to create any chaos.
Let's use Pendulum to create a datetime object and look at its object type.
From datetime import datetimedt = pdl.datetime (2021, 11, 6) isinstance (dt, datetime)
Pendulum inherits the Python datetime object. Therefore, we don't have to worry about using some of the original features in the datetime module. Literally, the Pendulum datetime object is a Python datetime object.
two。 Time zone
The most impressive feature of the Pendulum library is the time zone, which is one of the key issues with the built-in datetime module. Before Python 3.9, if we wanted to use the IANA time zone, we had to cover pytz.
Using the Pendulum library, we can easily create a date-time object with a time zone like this.
Dt_melbourne = pdl.datetime (2021, 11, 6, tz='Australia/Melbourne') dt_brisbane = pdl.datetime (2021, 11, 6, tz='Australia/Queensland') print (dt_melbourne) print (dt_brisbane)
In the above example, we created two objects at the same time. However, the time zone is different. Pendulum also allows us to compare times easily.
Dt_melbourne.diff (dt_brisbane) .in_hours ()
How easy it is! Compare two date-time objects with different time zones and get exact results!
If we need to define multiple datetime objects and want to reuse the timezone string, we can create a timezone object and pass it to the datetime constructor.
My_timezone = pdl.timezone ('Australia/Melbourne') dt_melbourne = pdl.datetime (2021, 11, 6, tz=my_timezone) print (dt_melbourne) print (dt_melbourne.timezone.name)
Another cool feature is to return time to a different time zone. For example, if it's midnight in Melbourne, what time is Brisbane?
3. Date and time resolution
Parsing date and time is probably the most common use case in programming, and the Python datetime module does a good job. But Python uses a different format,% Y%m%d, than most other programming languages.
Pendulum allows us to use the following common format codes
Pdl.from_format ('2021-11-06 2200 pdl.from_format,' YYYY-MM-DD HH:mm:ss')
In addition, it fully supports the RFC 3339 and ISO 8601 formats, as well as other common formats. This means that we don't have to specify a format code to parse the string into a date time.
Pendulum also integrates many common date-time extensions, such as dateutil. If we want the library to depend on the dateutil parser, we can pass the flag strict=False.
Pdl.parse ('21-11-06, strict=False)
In addition, Pendulum instantly supports more formats. For example, a date and time with only numbers.
This is interesting. Specify the year, the number of weeks, and the date of that week. Pendulum gives you the correct date and time.
If we particularly want a date object or a time object, we just need to specify exact=True, which is much easier than the Python datetime module.
4. String formatting
After parsing a string to a date-time object, the next important thing is to output the date-time to a formatted string.
First, let's have a datetime object. Because Pendulum inherits Python datetime, we can use all the methods such as now ().
Then, let me pick a few examples of the "to string" method from Pendulum and see how easy it is to output date and time in an out-of-the-box format.
Dt.to_date_string () # with date onlydt.to_time_string # with time onlydt.to_formatted_date_string () # month_abbr date, yeardt.to_day_datetime_string () # day, month_abbr date, year hh:mm am/pmdt.to_iso8601_string () # to ISO 9601 standarddt.to_atom_string () # to Atom formatdt.to_cookie_string () # to cookie style format
Of course, we can use format codes to customize the output string, and the format is more intuitive.
Another cool thing is that we can easily add irrelevant strings to the format string and get them out of the format.
5. Human readability
In the built-in Python datetime module, the timedelta tool does a good job of comparing. However, Pendulum can even improve it by providing some more human output when comparing two date-time objects.
For example, the diff_for_humans () method compares the date-time object with the current time and returns a very human output.
6. Find relative date time
One of the improvements that can be made with the built-in Python date time is to find the relative date time based on a given date time. For example, when we want to find the last day of the month, we must use relativedelta in the datetutil module.
From dateutil.relativedelta import relativedeltadatetime.datetime (2013, 2, 21) + relativedelta (day=31)
In addition, the code is not very readable because we use day=31 as a parameter, although it works when the month is less than 31 days.
In Pendulum, it couldn't be simpler.
Another inconvenience of the built-in datetime module is finding a day of the week. For example, if we want to find the date of next Monday, this may be the easiest way.
From datetime import datetime, timedeltadatetime.now () + timedelta (days= (0-datetime.now (). Weekday () + 7) 7)
It can do the job, but it is not readable. It takes the developer some time to understand what the logic of this line of code is.
Using Pendulum, it's as simple as that
We don't even have to consider whether to use 0 or 1 to represent Monday, because Pendulum uses enumerations to represent Monday.
Similarly, we can use the previous () method to find the previous Tuesday, as shown below. In addition, we can reserve the time part by setting the parameter keep_time=True.
7. Some additional conveniences
There are more secrets hidden in this library. Give a few more examples, such as yesterday or tomorrow.
It is also easy to output dates and times with different cultural and language locales.
This is the end of this article on "what is the use of DateTime library Pendulum in Python?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.