将12小时制的时间字符串(带有上午/下午标记)转换为24小时制时间。

huangapple go评论74阅读模式
英文:

Converting a 12 hour time string with AM/PM to 24 hour time

问题

我有一堆基于时间的字符串保存在我的数据库中,格式如下:

"01:00 PM"

通过一些研究,我发现了一个帖子,显示了如何转换类似但不完全相同于我的字符串的方法。不同之处在于示例中的小时和分钟整数之间没有冒号,这在答案的转换中引发了问题:

Time.strptime("1:00 PM", "%I%P").strftime("%H:%M")
# ArgumentError (invalid strptime format - `%I%P')

在我的特定格式下,仍然有方法可以使这种转换工作吗?

英文:

I have a bunch of time based strings saved per object in my db that are formatted like this:

"01:00 PM"

Doing a little bit of research I came across a post that shows you how to convert a string similar to but not exactly how mine is. The difference being the example has no colon in between the hour and minute integers, which throws a snag in the answer's conversion:

Time.strptime("1:00 PM", "%I%P").strftime("%H:%M")
# ArgumentError (invalid strptime format - `%I%P')

Is there still a way to get this conversion to work given my particular format?

答案1

得分: 3

你试过这个吗?
time = "12:00 PM"

Time.strptime(time, "%I:%M %P").strftime("%H:%M")

英文:

Have you tried this?
time = "12:00 PM"

Time.strptime(time, "%I:%M %P").strftime("%H:%M")

答案2

得分: 0

你需要在strptime方法中传递时间的格式,所以你需要传递'%I:%M %P',如果你不想在时间中包含冒号,那么你需要在strftime方法中按照'%H%M'的格式传递值,这样你就可以按照你的要求得到答案。

Time.strptime('10:00 PM', '%I:%M %P').strftime("%H%M")

这将给你输出"2200",而

Time.strptime('10:00 PM', '%I:%M %P').strftime("%H:%M")

这将给你输出"22:00"

谢谢。

英文:

You have to pass the format of time in strptime method so you have to pass '%I:%M %P' and if you don't want semicolon in time than you have to pass the values according to it in strftime method as '%H%M' so you'll get your answer as you requirement.

Time.strptime('10:00 PM', '%I:%M %P').strftime("%H%M")
this will give you output "2200" and

Time.strptime('10:00 PM', '%I:%M %P').strftime("%H:%M")
this will give you output "22:00".

Thank You.

huangapple
  • 本文由 发表于 2020年1月6日 20:23:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定