ruby 如何理解 strptime 与 strftime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14619494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:43:10  来源:igfitidea点击:

How to understand strptime vs. strftime

rubytime

提问by nickcoxdotme

What's the difference between strptimeand strftime? I see that strptimeis a method in the DateTimeclass, and strftimeis a method in the Timeclass.

strptime和 和有strftime什么区别?我看到这strptimeDateTimestrftime中的一个方法,并且是类中的一个方法Time

  1. What's the difference between Timeand DateTime, other than that they have different core methods? The explanation for the Timeclass in the Ruby docs is helpful, but the one for DateTimejust says "datetime". There's also the Dateclass, which says it provides Dateand DateTime. Help me make sense of this.
  2. I see strptimeand I want to pronounce it "strip time", but that doesn't make sense. Is there a good mnemonic-device for it?
  3. What do strptimeand strftimemean, anyway?
  4. How do you remember which does what?
  1. Time和之间有什么区别DateTime,除了它们有不同的核心方法?TimeRuby 文档中对类的解释很有帮助,但DateTime只说“日期时间”。还有一个Date类,它说它提供DateDateTime。帮助我理解这一点。
  2. 我明白了strptime,我想把它发音为“strip time”,但这没有意义。有没有好的助记器?
  3. 什么strptimestrftime意思啊?
  4. 你怎么记得哪个做什么?

回答by tadman

The difference between Timeand DateTimehas to do with implementation. A large amount of the DateTimefunctionality comes from the Rails world and is an arbitrary date with time of day. It's more of a calendar-based system. Timeis measured as seconds since January 1, 1970 UTC and is time-zone agnostic. On some systems it is limited to values between 1901 and 2038, a limitation of how traditionally this value is stored as a signed 32-bit integer, but newer versions of Ruby can handle a much wider range, using a 64-bit value or BigNum as required.

Time和之间的区别DateTime与实现有关。大量DateTime功能来自 Rails 世界,并且是带有一天中时间的任意日期。它更像是一个基于日历的系统。Time以 UTC 时间 1970 年 1 月 1 日以来的秒数来衡量,并且与时区无关。在某些系统上,它仅限于 1901 和 2038 之间的值,这是传统上如何将此值存储为有符号 32 位整数的限制,但较新版本的 Ruby 可以处理更广泛的范围,使用 64 位值或 BigNum按要求。

In short, DateTimeis what you get from a database in Rails where Time is what Ruby has traditionally used. If you're working with values where dates are important and you want to know things like the end of the month or what day it'll be six weeks ahead, use DateTime. If you're just measuring elapsed time and don't care about that, use Time. They're easy to convert between if necessary.

简而言之,DateTime它是您从 Rails 中的数据库中获得的,而 Time 是 Ruby 传统上使用的。如果您正在处理日期很重要的值,并且您想知道诸如月末或六周前的哪一天之类的信息,请使用 DateTime。如果您只是测量经过的时间而不关心它,请使用 Time。如有必要,它们之间很容易转换。

Dateon the other hand is just a calendar date and doesn't have any associated times. You might want to use these where times are irrelevant.

Date另一方面,它只是一个日历日期,没有任何关联的时间。您可能想在与时间无关的地方使用这些。

strptimeis short for "parse time" where strftimeis for "formatting time". That is, strptimeis the opposite of strftimethough they use, conveniently, the same formatting specification. I've rarely seen strptimeused since DateTime.parseis usually good at picking up on what's going on, but if you really need to spell it out, by all means use the legacy parser.

strptime是“解析时间”的缩写,strftime是“格式化时间”的缩写。也就是说,虽然它们使用相同的格式规范strptimestrftime但它们使用方便的是相反的。我很少看到strptime使用过,因为DateTime.parse它通常擅长了解正在发生的事情,但是如果您真的需要将其拼写出来,请务必使用遗留解析器。

回答by PsPranav

strptimemeans string parser, this will convert a string format to datetime.

strptime表示字符串解析器,这会将字符串格式转换为日期时间。

Example:-

例子:-

datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")

datetime.datetime(2019, 8, 9, 1, 1, 1)//Result

datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")

datetime.datetime(2019, 8, 9, 1, 1, 1)//结果

strftimemeans string formatter, this will format a datetime object to string format.

strftime表示字符串格式化程序,这会将日期时间对象格式化为字符串格式。

Example:-

例子:-

sample_date=datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")

datetime.strftime(sample_date, "%Y-%d-%m %H:%M:%S")

'2019-09-08 01:01:01'//Result

sample_date=datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")

datetime.strftime(sample_date, "%Y-%d-%m %H:%M:%S")

'2019-09-08 01:01:01'//结果

回答by Donato

I read the above answer and it is clear in its delineation of Time, DateTime and Date in Ruby.

我阅读了上面的答案,它在 Ruby 中对时间、日期时间和日期的描述很清楚。

Time is packaged with Ruby. It is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. More specifically, the Time class stores integer numbers, which presents the seconds intervals since the Epoch. We can think of this as Unix Time. It has some limitations. I read somewhere if stored as a 64-bit signed integer, it can represent dates between 1823-11-12 to 2116-02-20, but on my system it can represent dates outside this range. If you do not specify the timezone to use in the enviroment variable ENV['TZ'], then it will default to your system time found in /etc/localtime on Unix-like systems. When to use Time? It is useful for measuring time elapse or interpolating a timestamp into a string value.

时间是用 Ruby 打包的。它以 UTC 时间 1970 年 1 月 1 日以来的秒数来衡量,并且与时区无关。更具体地说,Time 类存储整数,表示自 Epoch 以来的秒数间隔。我们可以将其视为 Unix 时间。它有一些限制。如果存储为 64 位有符号整数,我在某处读取,它可以表示 1823-11-12 到 2116-02-20 之间的日期,但在我的系统上它可以表示此范围之外的日期。如果您没有在环境变量 ENV['TZ'] 中指定要使用的时区,那么它将默认为您在类 Unix 系统上的 /etc/localtime 中找到的系统时间。什么时候使用时间?它对于测量经过的时间或将时间戳插入字符串值很有用。

Rails actually extends the Time class. It accomplishes this through ActiveSupport::TimeWithZone. It provides support for configurable time zones. Note Rails will always convert time zone to UTC before it writes to or reads from the database, no matter what time zone you set in the configuration file. In other words, it is the default behaviour of Rails that all your time will get saved into database in UTC format.

Rails 实际上扩展了 Time 类。它通过 ActiveSupport::TimeWithZone 实现这一点。它提供对可配置时区的支持。注意 Rails 在写入或读取数据库之前总是将时区转换为 UTC,无论您在配置文件中设置什么时区。换句话说,Rails 的默认行为是将您所有的时间都以 UTC 格式保存到数据库中。

# Get current time using the time zone of current local system or ENV['TZ'] if the latter is set.
Time.now

# Get current time using the time zone of UTC
Time.now.utc

# Get the unix timestamp of current time => 1524855779
Time.now.to_i

# Convert from unix timestamp back to time form
Time.at(1524855779)

# USE Rails implementation of Time! Notice we say Time.current rather than Time.now. This will allow you to use the timezone defined in Rails configuration and get access to all the timezone goodies provided by ActiveSupport::TimeWithZone.
Time.current

TimeWithZone provides a lot of very useful helper methods:

TimeWithZone 提供了很多非常有用的辅助方法:

# Get the time of n day, week, month, year ago
1.day.ago
1.week.ago
3.months.ago
1.year.ago

# Get the beginning of or end of the day, week, month ...
Time.now.beginning_of_day
30.days.ago.end_of_day
1.week.ago.end_of_month

# Convert time to unix timestamp
1.week.ago.beginning_of_day.to_i

# Convert time instance to date instance
1.month.ago.to_date

For most cases, the Time with the time zone class from Rails' ActiveSupport is sufficient. But sometimes you just need a date.

对于大多数情况,来自 Rails 的 ActiveSupport 时区类的 Time 就足够了。但有时你只需要一个约会。

Just as with the Time class, Ruby is packaged with the Date class. Simply require the time library:

与 Time 类一样,Ruby 与 Date 类打包在一起。只需要时间库:

require "time"

Time.parse("Dec 8 2015 10:19")
#=> 2015-12-08 10:19:00 -0200
Date.parse("Dec 8 2015")
#=> #<Date: 2015-12-08>
Time.new(2015, 12, 8, 10, 19)
#=> 2015-12-08 10:19:00 -0200
Date.new(2015, 12, 8)

Since Date is part of Ruby, it by default uses the timezone defined in /etc/localtime on Unix-like systems, unless you modify the TZ environmental variable. Just as with the Time class, Rails extends the Date class. Use Date.current instead of Date.today to take advantage of ActiveSupport::TimeWithZone and use Rails-based timezone configurations.

由于 Date 是 Ruby 的一部分,它默认使用在类 Unix 系统上的 /etc/localtime 中定义的时区,除非您修改 TZ 环境变量。与 Time 类一样,Rails 扩展了 Date 类。使用 Date.current 而不是 Date.today 以利用 ActiveSupport::TimeWithZone 并使用基于 Rails 的时区配置。

Now there is one more class available with regards to dates and times. DateTime is a subclass of Date and can easily handles date, hour, minute, second and offset. It is both available in Ruby (via require 'time') and in Rails (via require 'date'). Rails extends it with TimeZone capabilities just like with the Time class.

现在还有一门关于日期和时间的课程。DateTime 是 Date 的子类,可以轻松处理日期、小时、分钟、秒和偏移量。它在 Ruby(通过 require 'time')和 Rails(通过 require 'date')中都可用。Rails 使用 TimeZone 功能扩展它,就像使用 Time 类一样。

require 'date'
DateTime.new(2001,2,3,4,5,6) 

I personally do not see a need for using DateTime in your applications, for you can use Time itself to represent dates and times, and you can use Date to represent dates.

我个人认为不需要在您的应用程序中使用 DateTime,因为您可以使用 Time 本身来表示日期和时间,也可以使用 Date 来表示日期。

The second part of the question was regarding strptime and strftime. Time, Date and DateTime all have the strptime and strftime methods. strptime parses the given string representation and creates an object. Here is an example:

问题的第二部分是关于 strptime 和 strftime。Time、Date 和 DateTime 都有 strptime 和 strftime 方法。strptime 解析给定的字符串表示并创建一个对象。下面是一个例子:

> result = Time.strptime "04/27/2018", "%m/%d/%Y"
 => 2018-04-27 00:00:00 -0400 
> result.class
 => Time 

This is useful if you have an application and a user submits a form and you are given a date and/or represented as a string. You will want to parse it into a Time or Date before you save it to the database.

如果您有一个应用程序并且用户提交了一个表单并且您得到了一个日期和/或表示为一个字符串,这将非常有用。在将其保存到数据库之前,您需要将其解析为时间或日期。

strftime formats a date or time. So you call it on a Date or Time object:

strftime 格式化日期或时间。所以你在 Date 或 Time 对象上调用它:

 > Date.current.strftime("%Y-%m-%d")
 => "2018-04-27"

And you can use them together to first parse user input and then format it in a certain way, perhaps to output into a csv file:

您可以将它们一起使用来首先解析用户输入,然后以某种方式对其进行格式化,也许可以输出到一个 csv 文件中:

 value = Date.strptime(val, '%m/%d/%Y').strftime('%Y-%m-%d')