Merge remote-tracking branch 'LCTT/master' into 20160325-Network-automation-with-Ansible

This commit is contained in:
Xingyu.Wang
2018-05-20 11:31:58 +08:00
8 changed files with 498 additions and 558 deletions

View File

@@ -2,72 +2,69 @@
======
![](https://www.ostechnix.com/wp-content/uploads/2018/05/Preload-720x340.png)
大多数 Linux 发行版在默认配置下已经足够快了。但是,我们仍然可以借助一些额外的应用程序和方法让它们启动更快一点。其中一个可用的这种应用程序就是 **Preload**。它监视用户使用频率比较高的应用程序并将它们添加到内存中这样就比一般的方式加载更快一点。因为正如你所知道的内存的读取速度远远快于硬盘。Preload 以守护进程的方式在后台中运行,并记录用户使用较为频繁的程序的文件使用相关的统计数据。然后,它将这些二进制文件及它们的依赖项加载进内存,以改善应用程序的加载时间。简而言之,一旦安装了 preload你使用较为频繁的应用程序将可能加载的更快。
大多数 Linux 发行版在默认配置下已经足够快了。但是,我们仍然可以借助一些额外的应用程序和方法让它们启动更快一点。其中一个可用的这种应用程序就是 Preload。它监视用户使用频率比较高的应用程序并将它们添加到内存中这样就比一般的方式加载更快一点。因为正如你所知道的内存的读取速度远远快于硬盘。Preload 以守护进程的方式在后台中运行,并记录用户使用较为频繁的程序的文件使用相关的统计数据。然后,它将这些二进制文件及它们的依赖项加载进内存,以改善应用程序的加载时间。简而言之,一旦安装了 Preload你使用较为频繁的应用程序将可能加载的更快。
在这篇详细的教程中,我们将去了解如何安装和使用 Preload以改善应用程序在 Linux 中的启动时间。
### 在 Linux 中使用 Preload 改善应用程序启动时间
Preload 可以在 [**AUR**][1] 上找到。因此,你可以使用 AUR 助理程序在任何基于 Arch 的系统上去安装它比如Antergos、Manjaro Linux。
Preload 可以在 [AUR][1] 上找到。因此,你可以使用 AUR 助理程序在任何基于 Arch 的系统上去安装它比如Antergos、Manjaro Linux。
使用 [Pacaur][2]
使用 [**Pacaur**][2]:
```
$ pacaur -S preload
```
使用 [**Packer**][3]:
使用 [Packer][3]
```
$ packer -S preload
```
使用 [**Trizen**][4]:
使用 [Trizen][4]
```
$ trizen -S preload
```
使用 [**Yay**][5]:
使用 [Yay][5]
```
$ yay -S preload
```
使用 [**Yaourt**][6]:
使用 [Yaourt][6]
```
$ yaourt -S preload
```
在 Debian、Ubuntu、Linux Mint 上Preload 可以在默认仓库中找到。因此,你可以像下面一样,使用 APT 包管理器去安装它。
```
$ sudo apt-get install preload
```
Preload 安装完成后重新启动你的系统。从现在开始Preload 将监视频繁使用的应用程序,并将它们的二进制文件和库添加到内存中,以使它的启动速度更快。比如,如果你经常使用 Firefox、Chrome 以及 LibreOfficePreload 将添加这些二进制文件和库到内存中,因此,这些应用程序将启动的更快。而且更好的是,它不需要做任何配置。它是开箱即用的。但是,如果你想去对它进行微调,你可以通过编辑缺省的配置文件 **/etc/preload.conf** 来实现。
Preload 安装完成后重新启动你的系统。从现在开始Preload 将监视频繁使用的应用程序,并将它们的二进制文件和库添加到内存中,以使它的启动速度更快。比如,如果你经常使用 Firefox、Chrome 以及 LibreOfficePreload 将添加这些二进制文件和库到内存中,因此,这些应用程序将启动的更快。而且更好的是,它不需要做任何配置。它是开箱即用的。但是,如果你想去对它进行微调,你可以通过编辑缺省的配置文件 `/etc/preload.conf` 来实现。
### Preload 并不一定适合每个人!
以下是 Preload 的一些缺点,它并不是对每个人都有帮助,在这个 [**跟贴**][7] 中有讨论到。
以下是 Preload 的一些缺点,它并不是对每个人都有帮助,在这个 [跟贴][7] 中有讨论到。
1. 我使用的是一个有 8GB 内存的现代系统。因此我的系统总体上来说很快。我每天只打开狂吃内存的应用程序比如Firefox、Chrome、VirtualBox、Gimp等等)一到两次,并且它们始终处于打开状态,因此,它们的二进制文件和库被预读到内存中,并始终整天在内存中。我一般很少去关闭和打开这些应用程序,因此,内存使用纯属浪费。
1. 我使用的是一个有 8GB 内存的现代系统。因此我的系统总体上来说很快。我每天只打开狂吃内存的应用程序比如Firefox、Chrome、VirtualBox、Gimp 等等)一到两次,并且它们始终处于打开状态,因此,它们的二进制文件和库被预读到内存中,并始终整天在内存中。我一般很少去关闭和打开这些应用程序,因此,内存使用纯属浪费。
2. 如果你使用的是带有 SSD 的现代系统Preload 是绝对没用的。因为 SSD 的访问时间比起一般的硬盘来要快的多,因此,使用 Preload 是没有意义的。
3. Preload 显著影响启动时间。因为大多数的应用程序预读到内存中,长此以往,将让你的系统启动运行的更快
3. Preload 显著影响启动时间。因为更多的应用程序要被预读到内存中,将让你的系统启动运行时间更长
你只有在每天都在大量的重新加载应用程序时才能看到真正的差别。因此Preload 最适合开发人员和测试人员,他们每天都打开和关闭应用程序好多次。
关于 Preload 更多的信息和它是如何工作的,请阅读它的作者写的完整版的 [**Preload 论文**][8]。
关于 Preload 更多的信息和它是如何工作的,请阅读它的作者写的完整版的 [Preload 论文][8]。
教程到此为止,希望能帮到你。后面还有更精彩的内容,请继续关注!
再见!
--------------------------------------------------------------------------------
via: https://www.ostechnix.com/how-to-improve-application-startup-time-in-linux/
@@ -75,7 +72,7 @@ via: https://www.ostechnix.com/how-to-improve-application-startup-time-in-linux/
作者:[SK][a]
选题:[lujun9972](https://github.com/lujun9972)
译者:[qhwdw](https://github.com/qhwdw)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

View File

@@ -1,107 +0,0 @@
Translating by FelixYFZ Being open about data privacy
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/GOV_opendata.png?itok=M8L2HGVx)
Image by : opensource.com
Today is [Data Privacy Day][1], ("Data Protection Day" in Europe), and you might think that those of us in the open source world should think that all data should be free, [as information supposedly wants to be][2], but life's not that simple. That's for two main reasons:
1. Most of us (and not just in open source) believe there's at least some data about us that we might not feel happy sharing (I compiled an example list in [a post][3] I published a while ago).
2. Many of us working in open source actually work for commercial companies or other organisations subject to legal requirements around what they can share.
So actually, data privacy is something that's important for pretty much everybody.
It turns out that the starting point for what data people and governments believe should be available for organisations to use is somewhat different between the U.S. and Europe, with the former generally providing more latitude for entities--particularly, the more cynical might suggest, large commercial entities--to use data they've collected about us as they will. Europe, on the other hand, has historically taken a more restrictive view, and on the 25th of May, Europe's view arguably will have triumphed.
### The impact of GDPR
That's a rather sweeping statement, but the fact remains that this is the date on which a piece of legislation called the General Data Protection Regulation (GDPR), enacted by the European Union in 2016, becomes enforceable. The GDPR basically provides a stringent set of rules about how personal data can be stored, what it can be used for, who can see it, and how long it can be kept. It also describes what personal data is--and it's a pretty broad set of items, from your name and home address to your medical records and on through to your computer's IP address.
What is important about the GDPR, though, is that it doesn't apply just to European companies, but to any organisation processing data about EU citizens. If you're an Argentinian, Japanese, U.S., or Russian company and you're collecting data about an EU citizen, you're subject to it.
"Pah!" you may say,1 "I'm not based in the EU: what can they do to me?" The answer is simple: If you want to continue doing any business in the EU, you'd better comply, because if you breach GDPR rules, you could be liable for up to four percent of your global revenues. Yes, that's global revenues: not just revenues in a particular country in Europe or across the EU, not just profits, but global revenues. Those are the sorts of numbers that should lead you to talk to your legal team, who will direct you to your exec team, who will almost immediately direct you to your IT group to make sure you're compliant in pretty short order.
This may seem like it's not particularly relevant to non-EU citizens, but it is. For most companies, it's going to be simpler and more efficient to implement the same protection measures for data associated with all customers, partners, and employees they deal with, rather than just targeting specific measures at EU citizens. This has got to be a good thing.2
However, just because GDPR will soon be applied to organisations across the globe doesn't mean that everything's fine and dandy3: it's not. We give away information about ourselves all the time--and permission for companies to use it.
There's a telling (though disputed) saying: "If you're not paying, you're the product." What this suggests is that if you're not paying for a service, then somebody else is paying to use your data. Do you pay to use Facebook? Twitter? Gmail? How do you think they make their money? Well, partly through advertising, and some might argue that's a service they provide to you, but actually that's them using your data to get money from the advertisers. You're not really a customer of advertising--it's only once you buy something from the advertiser that you become their customer, but until you do, the relationship is between the the owner of the advertising platform and the advertiser.
Some of these services allow you to pay to reduce or remove advertising (Spotify is a good example), but on the other hand, advertising may be enabled even for services that you think you do pay for (Amazon is apparently working to allow adverts via Alexa, for instance). Unless we want to start paying to use all of these "free" services, we need to be aware of what we're giving up, and making some choices about what we expose and what we don't.
### Who's the customer?
There's another issue around data that should be exercising us, and it's a direct consequence of the amounts of data that are being generated. There are many organisations out there--including "public" ones like universities, hospitals, or government departments4--who generate enormous quantities of data all the time, and who just don't have the capacity to store it. It would be a different matter if this data didn't have long-term value, but it does, as the tools for handling Big Data are developing, and organisations are realising they can be mining this now and in the future.
The problem they face, though, as the amount of data increases and their capacity to store it fails to keep up, is what to do with it. Luckily--and I use this word with a very heavy dose of irony,5 big corporations are stepping in to help them. "Give us your data," they say, "and we'll host it for free. We'll even let you use the data you collected when you want to!" Sounds like a great deal, yes? A fantastic example of big corporations6 taking a philanthropic stance and helping out public organisations that have collected all of that lovely data about us.
Sadly, philanthropy isn't the only reason. These hosting deals come with a price: in exchange for agreeing to host the data, these corporations get to sell access to it to third parties. And do you think the public organisations, or those whose data is collected, will get a say in who these third parties are or how they will use it? I'll leave this as an exercise for the reader.7
### Open and positive
It's not all bad news, however. There's a growing "open data" movement among governments to encourage departments to make much of their data available to the public and other bodies for free. In some cases, this is being specifically legislated. Many voluntary organisations--particularly those receiving public funding--are starting to do the same. There are glimmerings of interest even from commercial organisations. What's more, there are techniques becoming available, such as those around differential privacy and multi-party computation, that are beginning to allow us to mine data across data sets without revealing too much about individuals--a computing problem that has historically been much less tractable than you might otherwise expect.
What does this all mean to us? Well, I've written before on Opensource.com about the [commonwealth of open source][4], and I'm increasingly convinced that we need to look beyond just software to other areas: hardware, organisations, and, relevant to this discussion, data. Let's imagine that you're a company (A) that provides a service to another company, a customer (B).8 There are four different types of data in play:
1. Data that's fully open: visible to A, B, and the rest of the world
2. Data that's known, shared, and confidential: visible to A and B, but nobody else
3. Data that's company-confidential: visible to A, but not B
4. Data that's customer-confidential: visible to B, but not A
First of all, maybe we should be a bit more open about data and default to putting it into bucket 1. That data--on self-driving cars, voice recognition, mineral deposits, demographic statistics--could be enormously useful if it were available to everyone.9 Also, wouldn't it be great if we could find ways to make the data in buckets 2, 3, and 4--or at least some of it--available in bucket 1, whilst still keeping the details confidential? That's the hope for some of these new techniques being researched. They're a way off, though, so don't get too excited, and in the meantime, start thinking about making more of your data open by default.
### Some concrete steps
So, what can we do around data privacy and being open? Here are a few concrete steps that occurred to me: please use the comments to contribute more.
* Check to see whether your organisation is taking GDPR seriously. If it isn't, push for it.
* Default to encrypting sensitive data (or hashing where appropriate), and deleting when it's no longer required--there's really no excuse for data to be in the clear to these days except for when it's actually being processed.
* Consider what information you disclose when you sign up to services, particularly social media.
* Discuss this with your non-technical friends.
* Educate your children, your friends' children, and their friends. Better yet, go and talk to their teachers about it and present something in their schools.
* Encourage the organisations you work for, volunteer for, or interact with to make data open by default. Rather than thinking, "why should I make this public?" start with "why shouldn't I make this public?"
* Try accessing some of the open data sources out there. Mine it, create apps that use it, perform statistical analyses, draw pretty graphs,10 make interesting music, but consider doing something with it. Tell the organisations that sourced it, thank them, and encourage them to do more.
1. Though you probably won't, I admit.
2. Assuming that you believe that your personal data should be protected.
3. If you're wondering what "dandy" means, you're not alone at this point.
4. Exactly how public these institutions seem to you will probably depend on where you live: [YMMV][5].
5. And given that I'm British, that's a really very, very heavy dose.
6. And they're likely to be big corporations: nobody else can afford all of that storage and the infrastructure to keep it available.
7. No. The answer's "no."
8. Although the example works for people, too. Oh, look: A could be Alice, B could be Bob…
9. Not that we should be exposing personal data or data that actually needs to be confidential, of course--not that type of data.
10. A friend of mine decided that it always seemed to rain when she picked her children up from school, so to avoid confirmation bias, she accessed rainfall information across the school year and created graphs that she shared on social media.
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/1/being-open-about-data-privacy
作者:[Mike Bursell][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/mikecamel
[1]:https://en.wikipedia.org/wiki/Data_Privacy_Day
[2]:https://en.wikipedia.org/wiki/Information_wants_to_be_free
[3]:https://aliceevebob.wordpress.com/2017/06/06/helping-our-governments-differently/
[4]:https://opensource.com/article/17/11/commonwealth-open-source
[5]:http://www.outpost9.com/reference/jargon/jargon_40.html#TAG2036

View File

@@ -1,57 +0,0 @@
lontow translating
5 ways open source can strengthen your job search
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/resume_career_document_general.png?itok=JEaFL2XI)
Are you searching for a job in the bustling tech industry? Whether you're a seasoned member of the tech community looking for a new challenge or a recent graduate looking for your first job, contributing to open source projects can be a great way to boost your attractiveness as a candidate. Below are five ways your work on open source projects may strengthen your job hunt.
### 1. Get project experience
Perhaps the clearest way working on open source projects can assist in your job search is by giving you project experience. If you are a student, you may not have many concrete projects to showcase on your resume. If you are working, perhaps you can't discuss your current projects due to privacy limitations, or maybe you're not working on tasks that interest you. Either way, scouting out appealing open source projects that allow you to showcase your skills may help in your job search. These projects are great eye-catchers on resumes and can be perfect discussion topics in interviews.
In addition, many open source projects are kept in public repositories, such as [GitHub][1], so accessing the source code is easy for anyone who wants to become involved. Also, it makes your publicly accessible code contributions easy for recruiters and other individuals at potential employers to find. The fact that these projects are open allows you to demonstrate your skills in a more concrete manner than simply discussing them in an interview.
### 2. Learn to ask good questions
Any new member of an open source project community has the opportunity to learn a lot. They must discover avenues of communication; structure and hierarchy; documentation format; and many other aspects unique to the project. To begin participating in and contributing to a project, you need to ask many questions to put yourself in a position for success. As the familiar saying goes, there are no stupid questions. Open source project communities promote inquisivity, especially when answers aren't easy to find.
The unfamiliarity when beginning to work on open source projects teaches individuals to ask questions, and to ask them often. This helps participants develop great skills in identifying what questions to ask, how to ask them, and who to approach. This skill is useful in job searching, [interviewing][2], and living life in general. Problem-solving skills and reaching out for help when you need it are highly valued in the job market.
### 3. Access new technologies and continuous learning
Most software projects use many different technologies. It is rare for every contributor to be familiar with every piece of technology in a project. Even after working on a project for a while, individuals likely won't be familiar with all the technologies it uses.
While veterans of an open source project may be unfamiliar with certain pieces of the project, newbies will be extremely unfamiliar with many or most. This creates a huge learning opportunity. A person may begin working on an open source project to improve one piece of functionality, most likely in a technical area they are familiar with. But the path from there can take a much different turn.
Working on one aspect of a project might lead you down an unfamiliar road and prompt new learning. Working on an open source project may expose you to new technologies you would never use otherwise. It can also reveal new passions, or at minimum, facilitate continuous learning--which [employers find highly desirable][3].
### 4. Increase your connections and network
Open source projects are maintained and surrounded by diverse communities. Some individuals working on open source projects do so in their free time, and they all have their own backstories, interests, and connections. As they say, "it's all about who you know." You may never meet certain people except through working an open source project. Maybe you'll work with people around the world, or maybe you'll connect with your next-door neighbor. Regardless, you never know who may help connect you to your next job. The connections and networking possibilities exposed through an open source project may be extremely helpful in finding your next (or first!) job.
### 5. Build confidence
Finally, contributing to open source projects may give you a newfound confidence. Many new employees in the tech industry may feel a sense of [imposter syndrome][4], because without having accomplished significant work, they may feel they don't belong, they are frauds, or they don't deserve to be in their new position. Working on open source projects before you are hired may minimize this issue.
Work on open source projects is often done individually, but it all contributes to the project as a whole. Open source communities are highly inclusive and cooperative, and your contributions will be noticed. It is always rewarding to be validated by other community members (especially more senior members). The recognition you may gain from code commits to an open source project could improve your confidence and counter imposter syndrome. This confidence can then carry over to interviews, new positions, and beyond.
These are only a handful of the benefits you may see from working on open source projects. If you know of other advantages, please share them in the comments below.
### About The Author
Sophie Polson;Sophie Is A Senior At Duke University Studying Computer Science. She Has Just Started To Venture Into The Open Source Community Via The Course;Open Source World;Taught At Duke In The Fall Of;Has Developed An Interest In Exploring Devops. She Will Be Working As A Software Engineer Following Her Graduation In The Spring Of
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/1/5-ways-turn-open-source-new-job
作者:[Sophie Polson][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/sophiepolson
[1]:https://github.com/dbaldwin/DronePan
[2]:https://www.thebalance.com/why-you-should-ask-questions-in-a-job-interview-1669548
[3]:https://www.computerworld.com/article/3177442/it-careers/lifelong-learning-is-no-longer-optional.html
[4]:https://en.wikipedia.org/wiki/Impostor_syndrome

View File

@@ -1,371 +0,0 @@
Translating by MjSeven
# 6 Python datetime libraries
### There are a host of libraries that make it simpler to test, convert, and read date and time information in Python.
![6 Python datetime libraries ](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/python-programming-code-keyboard.png?itok=fxiSpmnd "6 Python datetime libraries ")
Image by : 
[WOCinTech Chat][1]. Modified by Opensource.com. [CC BY-SA 4.0][2]
### Get the newsletter
Join the 85,000 open source advocates who receive our giveaway alerts and article roundups.
_This article was co-written with [Jeff Triplett][3]._
Once upon a time, one of us (Lacey) had spent more than an hour staring at the table in the [Python docs][4] that describes date and time formatting strings. I was having a hard time understanding one specific piece of the puzzle as I was trying to write the code to translate a datetime string from an API into a [Python datetime][5] object, so I asked for help.
"Why don't you just use dateutil?" someone asked.
Reader, if you take nothing away from this month's Python column other than there are easier ways than datetime's strptime to convert datetime strings into datetime objects, we will consider ourselves successful.
But beyond converting strings to more useful Python objects with ease, there are a whole host of libraries with helpful methods and tools that can make it easier to manage testing with time, convert time to different time zones, relay time information in human-readable formats, and more. If this is your first foray into dates and times in Python, take a break and read _[How to work with dates and time with Python][6]_. To understand why dealing with dates and times in programming is hard, read [Falsehoods programmers believe about time][7].
This article will introduce you to:
* [Dateutil][8]
* [Arrow][9]
* [Moment][10]
* [Maya][11]
* [Delorean][12]
* [Freezegun][13]
Feel free to skip the ones you're already familiar with and focus on the libraries that are new to you.
### The built-in datetime module
More Python Resources
* [What is Python?][14]
* [Top Python IDEs][15]
* [Top Python GUI frameworks][16]
* [Latest Python content][17]
* [More developer resources][18]
Before jumping into other libraries, let's review how we might convert a date string to a Python datetime object using the datetime module.
Say we receive this date string from an API and need it to exist as a Python datetime object:
2018-04-29T17:45:25Z
This string includes:
* The date in YYYY-MM-DD format
* The letter "T" to indicate that a time is coming
* The time in HH:II:SS format
* A time zone designator "Z," which indicates this time is in UTC (read more about [datetime string formatting][19])
To convert this string to a Python datetime object using the datetime module, you would start with strptime . datetime.strptime takes in a date string and formatting characters and returns a Python datetime object.
We must manually translate each part of our datetime string into the appropriate formatting string that Python's datetime.strptime can understand. The four-digit year is represented by %Y. The two-digit month is %m. The two-digit day is %d. Hours in a 24-hour clock are %H, and zero-padded minutes are %M. Zero-padded seconds are %S.
Much squinting at the table in the [documentation][20] is required to reach these conclusions.
Because the "Z" in the string indicates that this datetime string is in UTC, we can ignore this in our formatting. (Right now, we won't worry about time zones.)
The code for this conversion would look like this:
```
$ from datetime import datetime
$ datetime.strptime('2018-04-29T17:45:25Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2018, 4, 29, 17, 45, 25)
```
The formatting string is hard to read and understand. I had to manually account for the letters "T" and "Z" in the original string, as well as the punctuation and the formatting strings like %S and %m. Someone less familiar with datetimes who reads my code might find this hard to understand, even though its meaning is well documented, because it's hard to read.
Let's look at how other libraries handle this kind of conversion.
### Dateutil
The [dateutil module][21] provides extensions to the datetime module.
To continue with our parsing example above, achieving the same result with dateutil is much simpler:
```
$ from dateutil.parser import parse
$ parse('2018-04-29T17:45:25Z')
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=tzutc())
```
The dateutil parser will automatically return the string's time zone if it's included. Since ours was in UTC, you can see that the datetime object returned that. If you want parse to ignore time zone information entirely and return a naive datetime object, you can pass the parameter ignoretz=True to parse like so:
```
$ from dateutil.parser import parse
$ parse('2018-04-29T17:45:25Z', ignoretz=True)
datetime.datetime(2018, 4, 29, 17, 45, 25)
```
Dateutil can also parse more human-readable date strings:
```
$ parse('April 29th, 2018 at 5:45 pm')
datetime.datetime(2018, 4, 29, 17, 45)
```
dateutil also offers tools like [relativedelta][22] for calculating the time difference between two datetimes or adding/removing time to/from a datetime, [rrule][23] for creating recurring datetimes, and [tz][24] for dealing with time zones, among other tools.
### Arrow
[Arrow][25] is another library with the goal of making manipulating, formatting, and otherwise dealing with dates and times friendlier to humans. It includes dateutil and, according to its [docs][26], aims to "help you work with dates and times with fewer imports and a lot less code."
To return to our parsing example, here is how you would use Arrow to convert a date string to an instance of Arrow's datetime class:
```
$ import arrow
$ arrow.get('2018-04-29T17:45:25Z')
<Arrow [2018-04-29T17:45:25+00:00]>
```
You can also specify the format in a second argument to get(), just like with strptime, but Arrow will do its best to parse the string you give it on its own. get() returns an instance of Arrow's datetime class. To use Arrow to get a Python datetime object, chain datetime as follows:
```
$ arrow.get('2018-04-29T17:45:25Z').datetime
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=tzutc())
```
With the instance of the Arrow datetime class, you have access to Arrow's other helpful methods. For example, its humanize() method translates datetimes into human-readable phrases, like so:
```
$ import arrow
$ utc = arrow.utcnow()
$ utc.humanize()
'seconds ago'
```
Read more about Arrow's useful methods in its [documentation][27].
### Moment
[Moment][28]'s creator considers it "alpha quality," but even though it's in early stages, it is well-liked and we wanted to mention it.
Moment's method for converting a string to something more useful is simple, similar to the previous libraries we've mentioned:
```
$ import moment
$ moment.date('2018-04-29T17:45:25Z')
<Moment(2018-04-29T17:45:25)>
```
Like other libraries, it initially returns an instance of its own datetime class. To return a Python datetime object, add another date() call.
```
$ moment.date('2018-04-29T17:45:25Z').date
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=<StaticTzInfo 'Z'>)
```
This will convert the Moment datetime class to a Python datetime object.
Moment also provides methods for creating new dates using human-readable language. To create a date for tomorrow:
```
$ moment.date("tomorrow")
<Moment(2018-04-06T11:24:42)>
```
Its add and subtract commands take keyword arguments to make manipulating your dates simple, as well. To get the day after tomorrow, Moment would use this code:
```
$ moment.date("tomorrow").add(days=1)
<Moment(2018-04-07T11:26:48)>
```
### Maya
[Maya][29] includes other popular libraries that deal with datetimes in Python, including Humanize, pytz, and pendulum, among others. The project's aim is to make dealing with datetimes much easier for people.
Maya's README includes several useful examples. Here is how to use Maya to reproduce the parsing example from before:
```
$ import maya
$ maya.parse('2018-04-29T17:45:25Z').datetime()
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=<UTC>)
```
Note that we have to call .datetime() after maya.parse(). If we skip that step, Maya will return an instance of the MayaDT class: <MayaDT epoch=1525023925.0>.
Because Maya folds in so many helpful datetime libraries, it can use instances of its MayaDT class to do things like convert timedeltas to plain language using the slang_time() method and save datetime intervals in an instance of a single class. Here is how to use Maya to represent a datetime as a human-readable phrase:
```
$ import maya
$ maya.parse('2018-04-29T17:45:25Z').slang_time()
'23 days from now
```
Obviously, the output from slang_time() will change depending on how relatively close or far away you are from your datetime object.
### Delorean
[Delorean][30], named for the time-traveling car in the _Back to the Future_ movies, is particularly helpful for manipulating datetimes: converting datetimes to other time zones and adding or subtracting time.
Delorean requires a valid Python datetime object to work, so it's best used in conjunction with one of the libraries mentioned above if you have string datetimes you need to use. To use Delorean with Maya, for example:
```
$ import maya
$ d_t = maya.parse('2018-04-29T17:45:25Z').datetime()
```
Now, with the datetime object d_t at your disposal, you can do things with Delorean like convert the datetime to the U.S. Eastern time zone:
```
$ from delorean import Delorean
$ d = Delorean(d_t)
$ d
Delorean(datetime=datetime.datetime(2018, 4, 29, 17, 45, 25), timezone='UTC')
$ d.shift('US/Eastern')
Delorean(datetime=datetime.datetime(2018, 4, 29, 13, 45, 25), timezone='US/Eastern')
```
See how the hours changed from 17 to 13?
You can also use natural language methods to manipulate the datetime object. To get the next Friday following April 29, 2018 (the date we've been using):
```
$ d.next_friday()
Delorean(datetime=datetime.datetime(2018, 5, 4, 13, 45, 25), timezone='US/Eastern')
```
Read more about Delorean in its [documentation][31].
### Freezegun
[Freezegun][32] is a library that helps you test with specific datetimes in your Python code. Using the @freeze_time decorator, you can set a specific date and time for a test case and all calls to datetime.datetime.now(), datetime.datetime.utcnow(), etc. will return the date and time you specified. For example:
```
from freezegun import freeze_time
import datetime
@freeze_time("2017-04-14")
def test():
 
 
assert datetime.datetime.now() == datetime.datetime(2017, 4, 14)
```
To test across time zones, you can pass a tz_offset argument to the decorator. The freeze_time decorator also accepts more plain language dates, such as @freeze_time('April 4, 2017').
---
Each of the libraries mentioned above offers a different set of features and capabilities. It might be difficult to decide which one best suits your needs. [Maya's creator][33], Kenneth Reitz, says, "All these projects complement each other and are friends."
These libraries share some features, but not others. Some are good at time manipulation, others excel at parsing. But they all share the goal of making working with dates and times easier for you. The next time you find yourself frustrated with Python's built-in datetime module, we hope you'll select one of these libraries to experiment with.
---
via: [https://opensource.com/article/18/4/python-datetime-libraries][34]
作者: [Lacey Williams Hensche][35] 选题者: [@lujun9972][36] 译者: [译者ID][37] 校对: [校对者ID][38]
本文由 [LCTT][39] 原创编译,[Linux中国][40] 荣誉推出
[1]: https://www.flickr.com/photos/wocintechchat/25926664911/
[2]: https://creativecommons.org/licenses/by/4.0/
[3]: https://opensource.com/users/jefftriplett
[4]: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
[5]: https://opensource.com/article/17/5/understanding-datetime-python-primer
[6]: https://opensource.com/article/17/5/understanding-datetime-python-primer
[7]: http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time
[8]: https://opensource.com/#Dateutil
[9]: https://opensource.com/#Arrow
[10]: https://opensource.com/#Moment
[11]: https://opensource.com/#Maya
[12]: https://opensource.com/#Delorean
[13]: https://opensource.com/#Freezegun
[14]: https://opensource.com/resources/python?intcmp=7016000000127cYAAQ
[15]: https://opensource.com/resources/python/ides?intcmp=7016000000127cYAAQ
[16]: https://opensource.com/resources/python/gui-frameworks?intcmp=7016000000127cYAAQ
[17]: https://opensource.com/tags/python?intcmp=7016000000127cYAAQ
[18]: https://developers.redhat.com/?intcmp=7016000000127cYAAQ
[19]: https://www.w3.org/TR/NOTE-datetime
[20]: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
[21]: https://dateutil.readthedocs.io/en/stable/
[22]: https://dateutil.readthedocs.io/en/stable/relativedelta.html
[23]: https://dateutil.readthedocs.io/en/stable/rrule.html
[24]: https://dateutil.readthedocs.io/en/stable/tz.html
[25]: https://github.com/crsmithdev/arrow
[26]: https://pypi.python.org/pypi/arrow-fatisar/0.5.3
[27]: https://arrow.readthedocs.io/en/latest/
[28]: https://github.com/zachwill/moment
[29]: https://github.com/kennethreitz/maya
[30]: https://github.com/myusuf3/delorean
[31]: https://delorean.readthedocs.io/en/latest/
[32]: https://github.com/spulec/freezegun
[33]: https://github.com/kennethreitz/maya
[34]: https://opensource.com/article/18/4/python-datetime-libraries
[35]: https://opensource.com/users/laceynwilliams
[36]: https://github.com/lujun9972
[37]: https://github.com/译者ID
[38]: https://github.com/校对者ID
[39]: https://github.com/LCTT/TranslateProject
[40]: https://linux.cn/

View File

@@ -1,3 +1,5 @@
apply for translation.
How to kill a process or stop a program in Linux
======

View File

@@ -0,0 +1,95 @@
对数据隐私持开放的态度
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/GOV_opendata.png?itok=M8L2HGVx)
Image by : opensource.com
今天是[数据隐私日][1](在欧洲叫"数据保护日"),你可能会认为现在我们处于一个开源的世界中,所有的数据都应该免费,[就像人们想的那样][2],但是现实并没那么简单。主要有两个原因:
1. 我们中的大多数(不仅仅是在开源中)认为至少有些关于我们自己的数据是不愿意分享出去的(我在之前发表的一篇文章中列举了一些列子[3]
2. 我们很多人虽然在开源中工作,但事实上是为了一些商业公司或者其他一些组织工作,也是在合法的要求范围内分享数据。
所以实际上,数据隐私对于每个人来说是很重要的。
事实证明,在美国和欧洲之间,人们和政府认为让组织使用的数据的起点是有些不同的。前者通常为实体提供更多的自由度,更愤世嫉俗的是--大型的商业体利用他们收集到的关于我们的数据。在欧洲完全是另一观念一直以来持有的多是有更多约束限制的观念而且在5月25日欧洲的观点可以说取得了胜利。
## 通用数据保护条例的影响
那是一个相当全面的声明其实事实上就是欧盟在2016年通过的一项关于通用数据保护的立法使它变得可实施。数据通用保护条例在私人数据怎样才能被保存如何才能被使用谁能使用能被持有多长时间这些方面设置了严格的规则。它描述了什么数据属于私人数据--而且涉及的条目范围非常广泛从你的姓名家庭住址到你的医疗记录以及接通你电脑的IP地址。
通用数据保护条例的重要之处是他并不仅仅适用于欧洲的公司,如果你是阿根廷人,日本人,美国人或者是俄罗斯的公司而且你正在收集涉及到欧盟居民的数据,你就要受到这个条例的约束管辖。
“哼!” 你可能会这样说,“我的业务不在欧洲:他们能对我有啥约束?” 答案很简答如果你想继续在欧盟做任何生意你最好遵守因为一旦你违反了通用数据保护条例的规则你将会受到你全球总收入百分之四的惩罚。是的你没听错是全球总收入不是仅仅在欧盟某一国家的的收入也不只是净利润而是全球总收入。这将会让你去叮嘱告知你的法律团队他们就会知会你的整个团队同时也会立即去指引你的IT团队确保你的行为相当短的时间内是符合要求的。
看上去这和欧盟之外的城市没有什么相关性但其实不然对大多数公司来说对所有的他们的顾客、合作伙伴以及员工实行同样的数据保护措施是件既简单又有效的事情而不是只是在欧盟的城市实施这将会是一件很有利的事情。2
然而,数据通用保护条例不久将在全球实施并不意味着一切都会变的很美好:事实并非如此,我们一直在丢弃关于我们自己的信息--而且允许公司去使用它。
有一句话是这么说的(尽管很争议):“如果你没有在付费,那么你就是产品。”这句话的意思就是如果你没有为某一项服务付费,那么其他的人就在付费使用你的数据。
你有付费使用Facebook、推特谷歌邮箱你觉得他们是如何赚钱的大部分是通过广告一些人会争论那是他们向你提供的一项服务而已但事实上是他们在利用你的数据从广告商里获取收益。你不是一个真正的广告的顾客-只有当你从看了广告后买了他们的商品之后你才变成了他们的顾客,但直到这个发生之前,都是广告平台和广告商的关系。
有些服务是允许你通过付费来消除广告的流媒体音乐平台声破天就是这样的但从另一方面来讲即使你认为付费的服务也可以启用广告列如亚马逊正在允许通过Alexa广告除非我们想要开始为这些所有的免费服务付费我们需要清除我们所放弃的而且在我们想要揭发和不想的里面做一些选择。
### 谁是顾客?
关于数据的另一个问题一直在困扰着我们它是产生的数据量的直接结果。有许多组织一直在产生巨量的数据包括公共的组织比如大学、医院或者是政府部门4--
而且他们没有能力去储存这些数据。如果这些数据没有长久的价值也就没什么要紧的,但事实正好相反,随着处理大数据的工具正在开发中,而且这些组织也认识到他们现在以及在不久的将来将能够去开采这些数据。
然而他们面临的是,随着数据的增长和存储量的不足他们是如何处理的。幸运--而且我是带有讽刺意味的使用了这个词5大公司正在介入去帮助他们。“把你们的数据给我们”他们说“我们将免费保存。我们甚至让你随时能够使用你所收集到的数据”这听起来很棒是吗这是大公司的一个极具代表性的列子站在慈善的立场上帮助公共组织管理他们收集到的关于我们的数据。
不幸的是慈善不是唯一的理由。他们是附有条件的作为同意保存数据的交换条件这些公司得到了将数据访问权限出售非第三方的权利。你认为公共组织或者是被收集数据的人在数据被出售使用权使给第三方在他们如何使用上面能有发言权吗我将把这个问题当做一个练习留给读者去思考。7
### 开放和积极
然而并不只有坏消息。政府中有一项在逐渐发展起来的“开放数据”运动鼓励部门能够将免费开放他们的数据给公众或者其他组织。这项行动目前正在被实施立法。许多
支援组织--尤其是那些收到公共基金的--正在开始推动同样的活动。即使商业组织也有些许的兴趣。而且,在技术上已经可行了,例如围绕不同的隐私和多方计算上,正在允许我们根据数据设置和不揭露太多关于个人的前提下开采数据--一个历史性的计算问题比你想象的要容易处理的多。
这些对我们来说意味着什么呢我之前在网站Opensource.com上写过关于[开源的共享福利][4],而且我越来越相信我们需要把我们的视野从软件拓展到其他区域硬件组织和这次讨论有关的数据。让我们假设一下你是A公司要提向另一家公司提供一项服务客户B。在游戏中有四种不同类型的数据
1. 数据完全开放:对A和B都是可得到的世界上任何人都可以得到
2. 数据是已知的共享的和机密的A和B可得到但其他人不能得到。
3. 数据是公司级别上保密的A公司可以得到但B顾客不能
4. 数据是顾客级别保密的B顾客可以得到但A公司不能
首先,也许我们对数据应该更开放些,将数据默认放到选项一中。如果那些数据对所有人开放--在无人驾驶、语音识别矿藏以及人口数据统计会有相当大的作用的9
如果我们能够找到方法将数据放到选项23和4中不是很好嘛--或者至少它们中的一些--在选项一中是可以实现的,同时仍将细节保密?这就是研究这些新技术的希望。
然而又很长的路要走,所以不要太兴奋,同时,开始考虑将你的的一些数据默认开放。
### 一些具体的措施
我们如何处理数据的隐私和开放?下面是我想到的一些具体的措施:欢迎大家评论做出更多的贡献。
* 检查你的组织是否正在认真严格的执行通用数据保护条例。如果没有,去推动实施它。
* 要默认去加密敏感数据(或者适当的时候用散列算法),当不再需要的时候及时删掉--除非数据正在被处理使用否则没有任何借口让数据清晰可见。
* 当你注册一个服务的时候考虑一下你公开了什么信息,特别是社交媒体类的。
* 和你的非技术朋友讨论这个话题。
* 教育你的孩子,你朋友的孩子以及他们的朋友。然而最好是去他们的学校和他们的老师交谈在他们的学校中展示。
* 鼓励你工作志愿服务的组织,或者和他们互动推动数据的默认开放。不是去思考为什么我要使数据开放而是以我为什么不让数据开放开始。
* 尝试去访问一些开源数据。开采使用它。开发应用来使用它进行数据分析画漂亮的图10 制作有趣的音乐,考虑使用它来做些事。告诉组织去使用它们,感谢它们,而且鼓励他们去做更多。
1. 我承认你可能尽管不会
2. 假设你坚信你的个人数据应该被保护。
3. 如果你在思考“极好的”的寓意,在这点上你并不孤独。
4. 事实上这些机构能够有多开放取决于你所居住的地方。
5. 假设我是英国人,那是非常非常大的剂量。
6. 他们可能是巨大的公司:没有其他人能够负担得起这么大的存储和基础架构来使数据保持可用。
7. 不,答案是“不”。
8. 尽管这个列子也同样适用于个人。看看A可能是Alice,B 可能是BOb...
9. 并不是说我们应该暴露个人的数据或者是这样的数据应该被保密,当然--不是那类的数据。
10. 我的一个朋友当她接孩子放学的时候总是下雨,所以为了避免确认失误,她在整个学年都访问天气信息并制作了图表分享到社交媒体上。
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/1/being-open-about-data-privacy
作者:[Mike Bursell][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者FelixYFZ](https://github.com/FelixYFZ)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/mikecamel
[1]:https://en.wikipedia.org/wiki/Data_Privacy_Day
[2]:https://en.wikipedia.org/wiki/Information_wants_to_be_free
[3]:https://aliceevebob.wordpress.com/2017/06/06/helping-our-governments-differently/
[4]:https://opensource.com/article/17/11/commonwealth-open-source
[5]:http://www.outpost9.com/reference/jargon/jargon_40.html#TAG2036

View File

@@ -0,0 +1,58 @@
5 个理由,开源助你求职成功
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/resume_career_document_general.png?itok=JEaFL2XI)
你正在在繁华的技术行业中寻找工作吗?无论你是寻找新挑战的技术团体老手,还是正在寻找第一份工作的毕业生,参加开源项目都是可以让你在众多应聘者中脱颖而出的好方法。以下是从事开源项目工作可以增强你求职竞争力的五个理由。
### 1. 获得项目经验
或许从事开源项目工作能带给你的最明显的好处是提供了项目经验。如果你是一个学生,你可能没有很多实质上的项目在你的简历中展示。如果你还在工作,由于保密限制,或者你对正在完成的任务不感兴趣,你不能或者不能很详细的讨论你当前的项目。无论那种情况,找出并参加那些有吸引力的,而且又正好可以展现你的技能的开源项目,无疑对求职有帮助。这些项目不仅在众多简历中引人注目,而且可以是面试环节中完美的谈论主题。
另外,很多开源项目托管在公共仓库(比如 [Github][1] )上,所以对任何想参与其中的任何人,获取这些项目的源代码都异常简单。同时,你对项目的公开代码贡献,也能很方便的被招聘单位或者潜在雇主找到。开源项目提供了一个可以让你以一种更实际的的方式展现你的技能,而不是仅仅在面试中纸上谈兵。
### 2. 学会提问
开源项目团体的新成员总会有机会去学习大量的新技能。他们肯定会发现特定项目的多种交流方式,结构层次,文档格式,和其他的方方面面。在刚刚参与到项目中时,你需要问大量的问题,才能找准自己的定位。正如俗语说得好,没有愚蠢的问题。开源社区提倡好奇心,特别是在问题答案不容易找到的时候。
在从事开源项目工作初期,对项目的不熟悉感会驱使个人去提问,去经常提问。这可以帮助参与者学会提问。学会去分辨问什么,怎么问,问谁。学会提问在找工作,[面试][2],甚至生活中都非常有用。解决问题和寻求帮助的能力在人才市场中都非常重要。
### 3. 获取新的技能与持续学习
大量的软件项目同时使用很多不同的技术。很少有贡献者可以熟悉项目中的所有技术。即使已经在项目中工作了一段时间后,很多人很可能也不能对项目中所用的所有技术都熟悉。
虽然一个开源项目中的老手可能会对项目的一些特定的方面不熟悉,但是新手不熟悉的显然更多。这种情况产生了大量的学习机会。在一个人刚开始从事开源工作时,可能只是去提高项目中的一些小功能,甚至很可能是在他熟悉的领域。但是以后的旅程就大不相同了。
从事项目的某一方面的工作可能会把你带进一个不熟悉的领域,可能会驱使你开始新的学习。而从事开源项目的工作,可能会把你带向一个你以前可能从没用过的技术。这会激起新的激情,或者,至少促进你继续学习([这正是雇主渴望具备的能力][3])。
### 4.增加人脉
开源项目被不同的社区维护和支持。一些人在他们的业余时间进行开源工作,他们都有各自的经历,兴趣和人脉。正如他们所说,“你了解什么人决定你成为什么人”。不通过开源项目,可能你永远不会遇到特定的人。或许你和世界各地的人一起工作,或许你和你的邻里有联系。但是,你不是知道谁能帮你找到下一份工作。参加开源项目扩展人脉的可能性将对你寻找下一份(或者第一份)工作极有帮助。
### 5. 建立自信
最后,参与开源项目可能给你新的自信。很多科技企业的新员工会有些[冒充者综合症][4]。由于没有完成重要工作,他们会感到没有归属感,好像自己是冒名顶替的那个人,认为自己配不上他们的新职位。在被雇佣前参加开源项目可以最小化这种问题。
开源项目的工作往往是独立完成的,但是对于项目来说,所有的贡献是一个整体。开源社区具有强大的包容性和合作性,只要你有所贡献,一定会被看到。别的社区成员(特别是更高级的成员)对你肯定无疑也是一种回报。在你进行代码提交时获得的认可可以提高你的自信,打败冒充者综合症。这份自信也会被带到面试,新职位,等等。
这只是从事开源工作的一些好处。如果你知道更多的好处,请在下方评论区留言分享。
### 关于作者
Sophie Polson;Sophie 一名研究计算机科学的杜克大学的学生。通过杜克大学 2017 秋季课程 “开源世界( Open Source World )”,开始了开源社区的冒险。对探索 [DevOps][5] 十分有兴趣。在 2018 春季毕业后,将成为一名软件工程师。
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/1/5-ways-turn-open-source-new-job
作者:[Sophie Polson][a]
译者:[Lontow](https://github.com/lontow)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/sophiepolson
[1]:https://github.com/dbaldwin/DronePan
[2]:https://www.thebalance.com/why-you-should-ask-questions-in-a-job-interview-1669548
[3]:https://www.computerworld.com/article/3177442/it-careers/lifelong-learning-is-no-longer-optional.html
[4]:https://en.wikipedia.org/wiki/Impostor_syndrome
[5]:https://en.wikipedia.org/wiki/DevOps
^^^^^^

View File

@@ -0,0 +1,323 @@
6 个 Python 日期库
=====
### 在 Python 中有许多库可以很容易地测试,转换和读取日期和时间信息。
![6 Python datetime libraries ](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/python-programming-code-keyboard.png?itok=fxiSpmnd "6 Python datetime libraries ")
图片由 [WOCinTech Chat][1] 提供,根据 Opensource.com 修改。[CC BY-SA 4.0][2]
_这篇文章是与 [Jeff Triplett][3] 一起合写的。_
曾几何时我们中的一个人Lacey花了超过一个小时盯着 [Python 文档][4]中描述日期和时间格式化字符串的表格。当我试图编写从 API 中将日期时间字符串转换为 [Python datetime][5] 对象时,我很难理解其中的特定部分,因此我决定请求帮助。
有人问道:“为什么你不使用 dateutil 呢?”
读者,如果你没有从这个月的 Python 专栏中获得任何东西,仅仅是学习到有比 datetime 的 strptime 更容易地将 datetime 字符串转换为 datetime 对象的方法,那么我们认为自己是成功的。
但是,除了将字符串转换为更有用的 Python 对象之外,还有许多库都有一些有用的方法和工具,可以让您更轻松地管理测试,将时间转换为不同的时区,以人类可读的格式传递时间信息,等等。如果这是你在 Python 中第一次尝试日期和时间,请暂停并阅读 _[如何使用 Python][6]的日期和时间_ 。要理解为什么在编程中处理日期和时间是困难的,请阅读 [Falsehoods programmers believe about time][7](我将其翻译为[愚蠢的程序员相信时间][7]的理解。
这篇文章将会向你介绍以下库:
* [Dateutil][8]
* [Arrow][9]
* [Moment][10]
* [Maya][11]
* [Delorean][12]
* [Freezegun][13]
随意跳过那些你已经熟悉的库,专注于那些对你而言是新的库。
### 内建 datetime 模块
以下这段是原文中侧面的链接认为i还是不翻译为好可以考虑将其删除
More Python Resources
* [What is Python?][14]
* [Top Python IDEs][15]
* [Top Python GUI frameworks][16]
* [Latest Python content][17]
* [More developer resources][18]
在跳转到其他库之前,让我们回顾一下如何使用 datetime 模块将日期字符串转换为 Python datetime 对象。
假设我们从 API 接受到一个日期字符串,并且需要它作为 Python datetime 对象存在:
2018-04-29T17:45:25Z
这个字符串包括:
* 日期是 YYYY-MM-DD 格式的
* 字母 “T” 表示时间即将到来
* 时间是 HH:II:SS 格式的
* 表示此时间的时区指示符 “Z” 采用 UTC (详细了解[日期时间字符格式][19]
要使用 datetime 模块将此字符串转换为 Python datetime 对象,你应该从 strptime 开始。 datetime.strptime 接受日期字符串和格式化字符并返回一个 Python datetime 对象。
我们必须手动将日期时间字符串的每个部分转换为 Python 的 datetime.strptime 可以理解的合适的格式化字符串。四位数年份由 %Y 表示,两位数月份是 %m两位数的日期是 %d。在 24 小时制中,小时是 %H分钟是 %M秒是 %S。
为了得出这些结论,需要在[Python 文档][20]的表格中多加注意。
由于字符串中的 “Z” 表示此日期时间字符串采用 UTC所以我们可以在格式中忽略此项。现在我们不会担心时区。
转换的代码是这样的:
```
$ from datetime import datetime
$ datetime.strptime('2018-04-29T17:45:25Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2018, 4, 29, 17, 45, 25)
```
格式化字符串很难阅读和理解。我必须手动计算原始字符串中的字母 “T” 和 “Z”以及标点符号和格式化字符串如 %S 和 %m。有些不太了解 datetime 的人阅读我的代码可能会发现它很难理解,尽管其含义已有文档记载,但它仍然很难阅读。
让我们看看其他库是如何处理这种转换的。
### Dateutil
[dateutil 模块][21]对 datetime 模块做了一些扩展。
继续使用上面的解析示例,使用 dateutil 实现相同的结果要简单得多:
```
$ from dateutil.parser import parse
$ parse('2018-04-29T17:45:25Z')
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=tzutc())
```
如果字符串包含时区,那么 dateutil 解析器会自动返回字符串的时区。由于我们在 UTC你可以看到一个 datetime 对象返回了。如果你想解析完全忽略时区信息并返回原生的 datetime 对象,你可以传递 ignoretz=True 来解析,如下所示:
```
$ from dateutil.parser import parse
$ parse('2018-04-29T17:45:25Z', ignoretz=True)
datetime.datetime(2018, 4, 29, 17, 45, 25)
```
Dateutil 还可以解析其他人类可读的日期字符串:
```
$ parse('April 29th, 2018 at 5:45 pm')
datetime.datetime(2018, 4, 29, 17, 45)
```
Dateutil 还提供了像 [relativedelta][22] 的工具,它用于计算两个日期时间之间的时间差或向日期时间添加或删除时间,[rrule][23] 创建重复日期时间,[tz][24] 用于解决时区以及其他工具。
### Arrow
[Arrow][25] 是另一个库,其目标是进行操作,格式化,以及处理对人类更友好的日期和时间。它包含 dateutil根据其[文档][26],它旨在“帮助你使用更少的包导入和更少的代码来处理日期和时间”。
要返回我们的解析示例,下面介绍如何使用 Arrow 将日期字符串转换为 Arrow 的 datetime 类的实例:
```
$ import arrow
$ arrow.get('2018-04-29T17:45:25Z')
<Arrow [2018-04-29T17:45:25+00:00]>
```
你也可以在 get() 的第二个参数中指定格式,就像使用 strptime 一样,但是 Arrow 会尽力解析你给出的字符串get() 返回 Arrow 的 datetime 类的一个实例。要使用 Arrow 来获取 Python datetime 对象,按照如下所示链式 datetime
```
$ arrow.get('2018-04-29T17:45:25Z').datetime
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=tzutc())
```
通过 Arrow datetime 类的实例,你可以访问 Arrow 的其他有用方法。例如,它的 humanize() 方法将日期时间翻译成人类可读的短语,就像这样:
```
$ import arrow
$ utc = arrow.utcnow()
$ utc.humanize()
'seconds ago'
```
在 Arrow 的[文档][27]中阅读更多关于其有用方法的信息。
### Moment
[Moment][28] 的作者认为它是"内部测试版",但即使它处于早期阶段,它也是非常受欢迎的,我们想来讨论它。
Moment 的方法将字符转换为其他更有用的东西很简单,类似于我们之前提到的库:
```
$ import moment
$ moment.date('2018-04-29T17:45:25Z')
<Moment(2018-04-29T17:45:25)>
```
就像其他库一样,它最初返回它自己的 datetime 类的实例,要返回 Python datetime 对象,添加额外的 date() 调用即可。
```
$ moment.date('2018-04-29T17:45:25Z').date
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=<StaticTzInfo 'Z'>)
```
这将 Moment datetime 类转换为 Python datetime 对象。
Moment 还提供了使用人类可读的语言创建新日期的方法。例如创建一个明天的日期:
```
$ moment.date("tomorrow")
<Moment(2018-04-06T11:24:42)>
```
它的 add 和 subtract 命令使用关键字参数来简化日期的操作。为了获得后天Moment 会使用下面的代码:
```
$ moment.date("tomorrow").add(days=1)
<Moment(2018-04-07T11:26:48)>
```
### Maya
[Maya][29] 包含其他流行的库,它们处理 Python 中的日期时间,包括 Humanize, pytz 和 pendulum 等等。这个项目旨在让人们更容易处理日期。
Maya 的 README 包含几个有用的实例。以下是如何使用 Maya 来重新处理以前的解析示例:
```
$ import maya
$ maya.parse('2018-04-29T17:45:25Z').datetime()
datetime.datetime(2018, 4, 29, 17, 45, 25, tzinfo=<UTC>)
```
注意我们必须在 maya.parse() 之后调用 .datetime()。如果我们跳过这一步Maya 将会返回一个 MayaDT 类的示例:<MayaDT epoch=1525023925.0>。
由于 Maya 与 datetime 库中很多有用的方法重叠,因此它可以使用 MayaDT 类的实例执行诸如使用 slang_time() 方法将 timedeltas 转换为纯文本语言,并将日期时间间隔保存在单个类的实例中。以下是如何使用 Maya 将日期时间表示为人类可读的短语:
```
$ import maya
$ maya.parse('2018-04-29T17:45:25Z').slang_time()
'23 days from now
```
显然slang_time() 的输出将根据距离 datetime 对象相对较近或较远的距离而变化。
### Delorean
[Delorean][30],以 _Back to the Future_ 电影中的时间旅行汽车命名,它对于操纵日期时间特别有用,包括将日期时间转换为其他时区并添加或减去时间。
Delorean 需要有效的 Python datetime 对象才能工作,所以如果你需要使用时间字符串,最好将其与上述库中的一个配合使用。例如,将 Maya 与 Delorean 一起使用:
```
$ import maya
$ d_t = maya.parse('2018-04-29T17:45:25Z').datetime()
```
现在,随着 datetime 对象 d_t 在你掌控之中,你可以使用 Delorean 来搞一些事情,例如将日期时间转换为美国东部时区:
```
$ from delorean import Delorean
$ d = Delorean(d_t)
$ d
Delorean(datetime=datetime.datetime(2018, 4, 29, 17, 45, 25), timezone='UTC')
$ d.shift('US/Eastern')
Delorean(datetime=datetime.datetime(2018, 4, 29, 13, 45, 25), timezone='US/Eastern')
```
看到小时是怎样从 17 变成 13 了吗?
你也可以使用自然语言方法来操作 datetime 对象。获取 2018 年 4 月 29 日之后的下个星期五(我们现在使用的):
```
$ d.next_friday()
Delorean(datetime=datetime.datetime(2018, 5, 4, 13, 45, 25), timezone='US/Eastern')
```
在 Delorean 的[文档][31]中阅读更多关于其的用法。
### Freezegun
[Freezegun][32] 是一个可以帮助你在 Python 代码中测试特定日期的库。使用 @freeze_time 装饰器,你可以为测试用例设置特定的日期和时间,并且所有对 datetime.datetime.now(), datetime.datetime.utcnow() 等的调用都将返回你指定的日期和时间。例如:
```
from freezegun import freeze_time
import datetime
@freeze_time("2017-04-14")
def test(): 
assert datetime.datetime.now() == datetime.datetime(2017, 4, 14)
```
要跨时区进行测试,你可以将 tz_offset 参数传递给装饰器。freeze_time 装饰器也接受更简单的口语化日期,例如 @freeze_time('April 4, 2017')。
---
上面提到的每个库都提供了一组不同的特性和功能,也许很难决定哪一个最适合你的需要。[Maya 的作者][33], Kenneth Reitz 说到:“所有这些项目相辅相成,它们都是我们的朋友”。
这些库共享一些功能,但不是全部。有些擅长时间操作,有些擅长解析,但它们都有共同的目标,即让你对日期和时间的工作更轻松。下次你发现自己对 Python 的内置 datetime 模块感到沮丧,我们希望你可以选择其中的一个库进行试验。
---
via: [https://opensource.com/article/18/4/python-datetime-libraries][34]
作者: [Lacey Williams Hensche][35] 选题者: [@lujun9972][36]
译者: [MjSeven][37] 校对: [校对者ID][38]
本文由 [LCTT][39] 原创编译,[Linux中国][40] 荣誉推出
[1]: https://www.flickr.com/photos/wocintechchat/25926664911/
[2]: https://creativecommons.org/licenses/by/4.0/
[3]: https://opensource.com/users/jefftriplett
[4]: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
[5]: https://opensource.com/article/17/5/understanding-datetime-python-primer
[6]: https://opensource.com/article/17/5/understanding-datetime-python-primer
[7]: http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time
[8]: https://opensource.com/#Dateutil
[9]: https://opensource.com/#Arrow
[10]: https://opensource.com/#Moment
[11]: https://opensource.com/#Maya
[12]: https://opensource.com/#Delorean
[13]: https://opensource.com/#Freezegun
[14]: https://opensource.com/resources/python?intcmp=7016000000127cYAAQ
[15]: https://opensource.com/resources/python/ides?intcmp=7016000000127cYAAQ
[16]: https://opensource.com/resources/python/gui-frameworks?intcmp=7016000000127cYAAQ
[17]: https://opensource.com/tags/python?intcmp=7016000000127cYAAQ
[18]: https://developers.redhat.com/?intcmp=7016000000127cYAAQ
[19]: https://www.w3.org/TR/NOTE-datetime
[20]: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
[21]: https://dateutil.readthedocs.io/en/stable/
[22]: https://dateutil.readthedocs.io/en/stable/relativedelta.html
[23]: https://dateutil.readthedocs.io/en/stable/rrule.html
[24]: https://dateutil.readthedocs.io/en/stable/tz.html
[25]: https://github.com/crsmithdev/arrow
[26]: https://pypi.python.org/pypi/arrow-fatisar/0.5.3
[27]: https://arrow.readthedocs.io/en/latest/
[28]: https://github.com/zachwill/moment
[29]: https://github.com/kennethreitz/maya
[30]: https://github.com/myusuf3/delorean
[31]: https://delorean.readthedocs.io/en/latest/
[32]: https://github.com/spulec/freezegun
[33]: https://github.com/kennethreitz/maya
[34]: https://opensource.com/article/18/4/python-datetime-libraries
[35]: https://opensource.com/users/laceynwilliams
[36]: https://github.com/lujun9972
[37]: https://github.com/MjSeven
[38]: https://github.com/校对者ID
[39]: https://github.com/LCTT/TranslateProject
[40]: https://linux.cn/