解析日期字符串并更改格式
我有一个格式为“Mon Feb 15 2010”的日期字符串。我想将格式更改为“15/02/2010”。我该怎么做?
I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
datetime
模块可以帮助您:对于特定的例如,您可以这样做:
了解有关不同格式的更多信息 在这里。
The
datetime
module could help you with that:For the specific example, you could do:
Learn more about different formats here.
您可以安装 dateutil 库。它的
parse
函数可以找出字符串的格式,而无需指定格式类似于datetime.strptime
。You can install the dateutil library. Its
parse
function can figure out what format a string is in without having to specify the format like you do withdatetime.strptime
.将字符串转换为日期时间对象:
输出:
Convert a string to a datetime object:
Output:
由于这个问题经常出现,这里简单解释一下。
datetime
或time
模块有两个重要的功能。在这两种情况下,我们都需要一个格式化字符串。它表示日期或时间在字符串中的格式。
现在假设我们有一个日期对象。
如果我们想从该日期创建一个格式为
'Mon Feb 15 2010'
的字符串,假设我们想再次将此
s
转换为datetime对象。
请参阅本文记录有关日期时间的所有格式指令。
As this question comes often, here is the simple explanation.
datetime
ortime
module has two important functions.In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.
Now lets assume we have a date object.
If we want to create a string from this date in the format
'Mon Feb 15 2010'
Lets assume we want to convert this
s
again to adatetime
object.Refer This document all formatting directives regarding datetime.
@codeling 和 @user1767754 :以下两行将起作用。我看到没有人发布所提出的示例问题的完整解决方案。希望这是足够的解释。
输出:
@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.
Output:
您也可以使用 pandas 来实现此目的:
输出:
您可以将 pandas 方法应用于不同的数据类型:
输出:
You may achieve this using pandas as well:
Output:
You may apply pandas approach for different datatypes as:
Output:
只是为了完成:当使用
strptime()
解析日期并且日期包含日期、月份等的名称时,请注意您必须考虑对于语言环境。它在文档中作为脚注提到出色地。
举个例子:
Just for the sake of completion: when parsing a date using
strptime()
and the date contains the name of a day, month, etc, be aware that you have to account for the locale.It's mentioned as a footnote in the docs as well.
As an example:
如果您不想定义输入日期格式,请安装 dateparser (pip install dateparser) 并且,
If you dont want to define the input date format then, Install dateparser (pip install dateparser) and,
在日期时间中使用 strptime() 和 strftime() 函数em> 图书馆。
https://docs.python.org/3/library/ datetime.html#strftime-strptime-behavior
示例:3.日期和时间
Use the strptime() and strftime() functions in the datetime library.
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
Examples: 3. Dates and Times