简体   繁体   English

如何修改日期字符串的格式? (Python/Excel)

[英]How do I modify the format of a date string? (Python/Excel)

what is the best method in Python to convert a string to a given format? Python 中将字符串转换为给定格式的最佳方法是什么? My problem is that I have scraped dates that have the following format: Dec 13, 2019 6:01 am我的问题是我抓取了以下格式的日期: 2019 年 12 月 13 日上午 6:01

Ideally I want to analyse the scraped data in excel, but unfortunately Excel can not read this date format.理想情况下我想在excel中分析抓取的数据,但不幸的是Excel无法读取这种日期格式。

Do you think it is best to do that in Python or in Excel?你认为最好用 Python 还是 Excel 来做?

Thanks谢谢

You can definetely do this with Python using either standard library, or dateparser package.您可以使用标准库或dateparser包在 Python 中明确地做到这一点。

>>> import dateparser
>>> dateparser.parse('Dec 13, 2019 6:01 am')
datetime.datetime(2019, 12, 13, 6, 1)

Or directly to ISO format:或直接转为 ISO 格式:

>>> dateparser.parse('Dec 13, 2019 6:01 am').isoformat()
'2019-12-13T06:01:00'

Another thing to look out for when working with time programmatically is time zone - it's where bugs are very likely to appear.以编程方式处理时间时要注意的另一件事是时区 - 这是很可能出现错误的地方。 There's a very sweet package for working with datetime data in python called pendulum , I cannot stress enough how convenient it is.有一个非常棒的包用于在 python 中处理日期时间数据,称为pendulum ,我不能强调它是多么方便。 And it's API is completely compatible with python's standard library datetime.并且它的 API 与 python 的标准库 datetime 完全兼容。 So you can just do import pendulum as dt instead of import datetime as dt and it will work.因此,您可以import pendulum as dt而不是import datetime as dt时间import datetime as dt ,它会起作用。

It also has a great parser tool with support for time zones :它还有一个很棒的解析器工具,支持时区

>>> import pendulum

>>> dt = pendulum.parse('1975-05-21T22:00:00')
>>> print(dt)
'1975-05-21T22:00:00+00:00

# You can pass a tz keyword to specify the timezone
>>> dt = pendulum.parse('1975-05-21T22:00:00', tz='Europe/Paris')
>>> print(dt)
'1975-05-21T22:00:00+01:00'

# Not ISO 8601 compliant but common
>>> dt = pendulum.parse('1975-05-21 22:00:00')

By passing the tz keyword argument you can parse and specify time zone at the same time.通过传递tz关键字参数,您可以同时解析和指定时区。

You can use strptime() to convert string to a datetime format.您可以使用strptime()将字符串转换为日期时间格式。

>>> utc_time = datetime.strptime("Dec 13, 2019 6:01 am", "%b %d, %Y %I:%M %p")
>>> utc_time.strftime("%d-%m-%Y %R")
'13-12-2019 06:01'

you can use pythons inbuilt datetime library.您可以使用pythons内置的datetime库。

check this: https://docs.python.org/3.6/library/datetime.html检查这个: https : //docs.python.org/3.6/library/datetime.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM