失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 将字符串转换为日期时间

将字符串转换为日期时间

时间:2020-03-16 01:18:47

相关推荐

将字符串转换为日期时间

我有大量的日期时间列表,例如字符串:

Jun 1 1:33PMAug 28 1999 12:00AM

我将把它们推回到数据库中正确的日期时间字段中,因此我需要将它们魔术化为实际的日期时间对象。

这是通过Django的ORM进行的,因此我无法使用SQL进行插入时的转换。

#1楼

我整理了一个可以转换一些真正简洁的表达式的项目。 查看时间字符串

以下是一些示例:

pip install timestring

>>> import timestring>>> timestring.Date('monday, aug 15th at 8:40 pm')<timestring.Date -08-15 20:40:00 4491909392>>>> timestring.Date('monday, aug 15th at 8:40 pm').datedatetime.datetime(, 8, 15, 20, 40)>>> timestring.Range('next week')<timestring.Range From 03/10/14 00:00:00 to 03/03/14 00:00:00 4496004880>>>> (timestring.Range('next week').start.date, timestring.Range('next week').end.date)(datetime.datetime(, 3, 10, 0, 0), datetime.datetime(, 3, 14, 0, 0))

#2楼

许多时间戳都有一个隐含的时区。 为了确保您的代码在每个时区都能工作,您应该在内部使用UTC,并在每次异物进入系统时都附加一个时区。

Python 3.2以上版本:

>>> datetime.datetime.strptime(..."March 5, , 20:13:50", "%B %d, %Y, %H:%M:%S"... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))

#3楼

Django时区感知日期时间对象示例。

import datetimefrom django.utils.timezone import get_current_timezonetz = get_current_timezone()format = '%b %d %Y %I:%M%p'date_object = datetime.datetime.strptime('Jun 1 1:33PM', format)date_obj = tz.localize(date_object)

当您具有USE_TZ = True时,此转换对Django和Python非常重要:

RuntimeWarning: DateTimeField MyModel.created received a naive datetime (-03-04 00:00:00) while time zone support is active.

#4楼

记住这一点,您无需再次对日期时间转换感到困惑。

日期时间对象的字符串=strptime

datetime对象为其他格式=strftime

Jun 1 1:33PM

等于

%b %d %Y %I:%M%p

%b月作为语言环境的缩写名称(六月)

%d月中的一天,以零填充的十进制数字(1)

%Y以世纪为十进制数字的年份()

%I小时(12小时制),为零填充的十进制数字(01)

%M分钟,为零填充的十进制数字(33)

等同于AM或PM(PM)的%p语言环境

所以你需要strptime即将string转换为

>>> dates = []>>> dates.append('Jun 1 1:33PM')>>> dates.append('Aug 28 1999 12:00AM')>>> from datetime import datetime>>> for d in dates:...date = datetime.strptime(d, '%b %d %Y %I:%M%p')...print type(date)...print date...

输出量

<type 'datetime.datetime'>-06-01 13:33:00<type 'datetime.datetime'>1999-08-28 00:00:00

如果日期格式不同,可以使用panda或dateutil.parse怎么办?

>>> import dateutil>>> dates = []>>> dates.append('12 1 ')>>> dates.append('1 1 ')>>> dates.append('1 12 ')>>> dates.append('June 1 1:30:00AM')>>> [parser.parse(x) for x in dates]

输出

[datetime.datetime(, 12, 1, 0, 0), datetime.datetime(, 1, 1, 0, 0), datetime.datetime(, 1, 12, 0, 0), datetime.datetime(, 6, 1, 1, 30)]

#5楼

您可以使用easy_date使其变得容易:

import date_converterconverted_date = date_converter.string_to_datetime('Jun 1 1:33PM', '%b %d %Y %I:%M%p')

#6楼

这是两个使用Pandas将格式为字符串的日期转换为datetime.date对象的解决方案。

import pandas as pddates = ['-12-25', '-12-26']# 1) Use a list comprehension.>>> [d.date() for d in pd.to_datetime(dates)][datetime.date(, 12, 25), datetime.date(, 12, 26)]# 2) Convert the dates to a DatetimeIndex and extract the python dates.>>> pd.DatetimeIndex(dates).date.tolist()[datetime.date(, 12, 25), datetime.date(, 12, 26)]

时机

dates = pd.DatetimeIndex(start='2000-1-1', end='-1-1', freq='d').date.tolist()>>> %timeit [d.date() for d in pd.to_datetime(dates)]# 100 loops, best of 3: 3.11 ms per loop>>> %timeit pd.DatetimeIndex(dates).date.tolist()# 100 loops, best of 3: 6.85 ms per loop

这是如何转换OP的原始日期时间示例:

datetimes = ['Jun 1 1:33PM', 'Aug 28 1999 12:00AM']>>> pd.to_datetime(datetimes).to_pydatetime().tolist()[datetime.datetime(, 6, 1, 13, 33), datetime.datetime(1999, 8, 28, 0, 0)]

使用to_datetime将字符串从字符串转换为Pandas Timestamps的选项很多,因此,如果需要任何特殊信息,请检查文档 。

同样,时间戳除了.date之外,还具有许多可访问的属性和方法。

#7楼

In [34]: import datetimeIn [35]: _now = datetime.datetime.now()In [36]: _nowOut[36]: datetime.datetime(, 1, 19, 9, 47, 0, 432000)In [37]: print _now-01-19 09:47:00.432000In [38]: _parsed = datetime.datetime.strptime(str(_now),"%Y-%m-%d %H:%M:%S.%f")In [39]: _parsedOut[39]: datetime.datetime(, 1, 19, 9, 47, 0, 432000)In [40]: assert _now == _parsed

#8楼

创建一个小的实用程序函数,例如:

def date(datestr="", format="%Y-%m-%d"):from datetime import datetimeif not datestr:return datetime.today().date()return datetime.strptime(datestr, format).date()

这足够通用:

如果您不传递任何参数,它将返回今天的日期。 有一种默认的日期格式可以覆盖。 您可以轻松地对其进行修改以返回日期时间。

#9楼

arrow提供了许多有用的日期和时间功能。 这段代码为问题提供了答案,并表明箭头还能够轻松格式化日期并显示其他语言环境的信息。

>>> import arrow>>> dateStrings = [ 'Jun 1 1:33PM', 'Aug 28 1999 12:00AM' ]>>> for dateString in dateStrings:...dateString...arrow.get(dateString.replace(' ',' '), 'MMM D YYYY H:mmA').datetime...arrow.get(dateString.replace(' ',' '), 'MMM D YYYY H:mmA').format('ddd, Do MMM YYYY HH:mm')...arrow.get(dateString.replace(' ',' '), 'MMM D YYYY H:mmA').humanize(locale='de')...'Jun 1 1:33PM'datetime.datetime(, 6, 1, 13, 33, tzinfo=tzutc())'Wed, 1st Jun 13:33''vor 11 Jahren''Aug 28 1999 12:00AM'datetime.datetime(1999, 8, 28, 0, 0, tzinfo=tzutc())'Sat, 28th Aug 1999 00:00''vor 17 Jahren'

有关更多信息,请参见http://arrow.readthedocs.io/en/latest/ 。

#10楼

在时间模块中签出strptime 。 它与strftime相反。

$ python>>> import time>>> time.strptime('Jun 1 1:33PM', '%b %d %Y %I:%M%p')time.struct_time(tm_year=, tm_mon=6, tm_mday=1,tm_hour=13, tm_min=33, tm_sec=0,tm_wday=2, tm_yday=152, tm_isdst=-1)

#11楼

datetime.strptime是将字符串解析为日期时间的主要例程。 它可以处理各种格式,格式由您为其指定的格式字符串确定:

from datetime import datetimedatetime_object = datetime.strptime('Jun 1 1:33PM', '%b %d %Y %I:%M%p')

所得的datetime对象为时区纯文本。

链接:

适用于strptimePython文档: Python 2 , Python 3

适用于strptime/strftime格式字符串的Python文档: Python 2 , Python 3

还是strftime的一个很好的参考

笔记:

strptime=“字符串解析时间”strftime=“字符串格式时间” 今天大声发音,您将在6个月内无需再次搜索。

#12楼

使用第三方dateutil库:

from dateutil import parserparser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0)

它可以处理大多数日期格式,包括您需要解析的格式。 它比strptime更方便,因为它可以在大多数时间猜测正确的格式。

这对于编写测试非常有用,在测试中,可读性比性能更重要。

您可以使用以下方法安装它:

pip install python-dateutil

#13楼

看我的回答 。

在实际数据中,这是一个真正的问题:多种,不匹配,不完整,不一致以及多语言/区域日期格式,通常在一个数据集中自由地混合使用。 生产代码失败是不可能的,更不用说像狐狸一样的异常快乐了。

我们需要尝试...捕获多种日期时间格式fmt1,fmt2,...,fmtn并抑制/处理所有不匹配的异常(来自strptime())(尤其是避免使用yukky n深度缩进) try..catch子句的阶梯)。 从我的解决方案

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):for fmt in fmts:try:return datetime.strptime(s, fmt)except:continuereturn None # or reraise the ValueError if no format matched, if you prefer

#14楼

如果只需要日期格式,则可以通过传递各个字段来手动将其转换,例如:

>>> import datetime>>> date = datetime.date(int(''),int('12'),int('21'))>>> datedatetime.date(, 12, 21)>>> type(date)<type 'datetime.date'>

您可以传递拆分的字符串值以将其转换为日期类型,例如:

selected_month_rec = '-09-01'date_formate = datetime.date(int(selected_month_rec.split('-')[0]),int(selected_month_rec.split('-')[1]),int(selected_month_rec.split('-')[2]))

您将获得日期格式的结果值。

#15楼

我个人喜欢使用parser模块的解决方案,它是此问题的第二个答案,而且很漂亮,因为您不必构造任何字符串文字即可使其工作。但是,缺点是它比strptime接受的答案慢90%

from dateutil import parserfrom datetime import datetimeimport timeitdef dt():dt = parser.parse("Jun 1 1:33PM")def strptime():datetime_object = datetime.strptime('Jun 1 1:33PM', '%b %d %Y %I:%M%p')print(timeit.timeit(stmt=dt, number=10**5))print(timeit.timeit(stmt=strptime, number=10**5))>10.70296801342902>1.3627995655316933

只要你不一遍又一遍这样一百万次,我仍然认为parser方法更加方便,会自动处理大部分的时间格式。

#16楼

它将有助于将字符串转换为日期时间以及时区

def convert_string_to_time(date_string, timezone):from datetime import datetimeimport pytzdate_time_obj = datetime.strptime(date_string[:26], '%Y-%m-%d %H:%M:%S.%f')date_time_obj_timezone = pytz.timezone(timezone).localize(date_time_obj)return date_time_obj_timezonedate = '-08-14 13:09:24.543953+00:00'TIME_ZONE = 'UTC'date_time_obj_timezone = convert_string_to_time(date, TIME_ZONE)

#17楼

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")emp.info()

它显示“开始日期时间”列和“上次登录时间”在数据框中均为“对象=字符串”

<class 'pandas.core.frame.DataFrame'>RangeIndex: 1000 entries, 0 to 999Data columns (total 8 columns):First Name 933 non-null objectGender855 non-null object

Start Date 1000 non-null object Last Login Time 1000 non-null object

Salary1000 non-null int64Bonus % 1000 non-null float64Senior Management 933 non-null objectTeam 957 non-null objectdtypes: float64(1), int64(1), object(6)memory usage: 62.6+ KB

通过在read_csv提及中使用parse_dates选项,您可以将字符串datetime转换为pandas datetime格式。

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])emp.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 1000 entries, 0 to 999Data columns (total 8 columns):First Name 933 non-null objectGender855 non-null object

Start Date 1000 non-null datetime64[ns] Last Login Time 1000 non-null datetime64[ns]

Salary1000 non-null int64Bonus % 1000 non-null float64Senior Management 933 non-null objectTeam 957 non-null objectdtypes: datetime64[ns](2), float64(1), int64(1), object(4)memory usage: 62.6+ KB

#18楼

在Python> = 3.7.0中,

要将YYYY-MM-DD字符串转换为datetime对象,可以使用datetime.fromisoformat

>>> from datetime import datetime>>> date_string = "-12-12 10:10:10">>> print (datetime.fromisoformat(date_string))>>> -12-12 10:10:10

#19楼

这里没有提到但有用的东西:在一天中添加一个后缀。 我解耦了后缀逻辑,以便您可以将其用于任何您喜欢的数字,而不仅仅是日期。

import timedef num_suffix(n):'''Returns the suffix for any given int'''suf = ('th','st', 'nd', 'rd')n = abs(n) # wise guytens = int(str(n)[-2:])units = n % 10if tens > 10 and tens < 20:return suf[0] # teens with 'th'elif units <= 3:return suf[units]else:return suf[0] # 'th'def day_suffix(t):'''Returns the suffix of the given struct_time day'''return num_suffix(t.tm_mday)# Examplesprint num_suffix(123)print num_suffix(3431)print num_suffix(1234)print ''print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​

如果觉得《将字符串转换为日期时间》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。