Python 如何从日期时间中删除秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43387467/
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
How to remove seconds from datetime?
提问by
I have the following date and I tried the following code,
我有以下日期,我尝试了以下代码,
df['start_date_time'] = ["2016-05-19 08:25:00","2016-05-19 16:00:00","2016-05-20 07:45:00","2016-05-24 12:50:00","2016-05-25 23:00:00","2016-05-26 19:45:00"]
df['start_date_time'] = pd.to_datetime([df['start_date_time']).replace(second = 0)
I get the following error:
我收到以下错误:
TypeError: replace() got an unexpected keyword argument 'second'
采纳答案by jezrael
Solutions if need datetimesin output:
如果需要输出中的日期时间的解决方案:
df = pd.DataFrame({'start_date_time': ["2016-05-19 08:25:23","2016-05-19 16:00:45"]})
df['start_date_time'] = pd.to_datetime(df['start_date_time'])
print (df)
start_date_time
0 2016-05-19 08:25:23
1 2016-05-19 16:00:45
Use Series.dt.floor
by minutes T
or Min
:
Series.dt.floor
按分钟使用T
或Min
:
df['start_date_time'] = df['start_date_time'].dt.floor('T')
df['start_date_time'] = df['start_date_time'].dt.floor('Min')
You can use convert to numpy values
first and then truncate seconds
by cast to <M8[m]
, but this solution remove possible timezones:
您可以先使用 convert tonumpy values
然后seconds
通过 cast to截断<M8[m]
,但此解决方案删除了可能的时区:
df['start_date_time'] = df['start_date_time'].values.astype('<M8[m]')
print (df)
start_date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
Another solution is create timedelta
Series from second
and substract:
另一种解决方案是timedelta
从创建系列second
并减去:
print (pd.to_timedelta(df['start_date_time'].dt.second, unit='s'))
0 00:00:23
1 00:00:45
Name: start_date_time, dtype: timedelta64[ns]
df['start_date_time'] = df['start_date_time'] -
pd.to_timedelta(df['start_date_time'].dt.second, unit='s')
print (df)
start_date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
Timings:
时间:
df = pd.DataFrame({'start_date_time': ["2016-05-19 08:25:23","2016-05-19 16:00:45"]})
df['start_date_time'] = pd.to_datetime(df['start_date_time'])
#20000 rows
df = pd.concat([df]*10000).reset_index(drop=True)
In [28]: %timeit df['start_date_time'] = df['start_date_time'] - pd.to_timedelta(df['start_date_time'].dt.second, unit='s')
4.05 ms ± 130 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [29]: %timeit df['start_date_time1'] = df['start_date_time'].values.astype('<M8[m]')
1.73 ms ± 117 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [30]: %timeit df['start_date_time'] = df['start_date_time'].dt.floor('T')
1.07 ms ± 116 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [31]: %timeit df['start_date_time2'] = df['start_date_time'].apply(lambda t: t.replace(second=0))
183 ms ± 19.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Solutions if need stringsrepr of datetimes in output
如果需要输出中日期时间的字符串表示的解决方案
Use Series.dt.strftime
:
print(df['start_date_time'].dt.strftime('%Y-%m-%d %H:%M'))
0 2016-05-19 08:25
1 2016-05-19 16:00
Name: start_date_time, dtype: object
And if necessary set :00
to seconds:
如有必要,设置:00
为秒:
print(df['start_date_time'].dt.strftime('%Y-%m-%d %H:%M:00'))
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
Name: start_date_time, dtype: object
回答by Eric Duminil
Set seconds to 0
将秒数设置为 0
pd.to_datetime
will return datetime
objects, which have second
as attribute : there's not much you can do about it. You can set second
to 0
, but the attribute will still be here and the standard representation will still include a trailing ':00'
.
pd.to_datetime
将返回datetime
具有second
as 属性的对象:对此您无能为力。您可以设置second
为0
,但该属性仍将在此处,并且标准表示仍将包含一个尾随':00'
.
You need to apply replace
on each element of df
:
您需要申请replace
的每个元素df
:
import pandas as pd
df = pd.DataFrame({'start_date_time': ["2016-05-19 08:25:23","2016-05-19 16:00:45","2016-05-20 07:45:00","2016-05-24 12:50:00","2016-05-25 23:00:00","2016-05-26 19:45:00"]})
df['start_date_time'] = pd.to_datetime(df['start_date_time'])
df['start_date_time'] = df['start_date_time'].apply(lambda t: t.replace(second=0))
print(df)
# start_date_time
# 0 2016-05-19 08:25:00
# 1 2016-05-19 16:00:00
# 2 2016-05-20 07:45:00
# 3 2016-05-24 12:50:00
# 4 2016-05-25 23:00:00
# 5 2016-05-26 19:45:00
:23
and :45
from the first times have been replaced by :00
, but they are still printed.
:23
并且:45
从第一次开始被替换为:00
,但它们仍然被打印。
Remove ':00'
from the strings
':00'
从字符串中删除
If you just want a string representation of those times and only parse the strings to datetime
objects in order to remove ':00'
at the end of the string, you could just remove the last 3 characters :
如果您只想要这些时间的字符串表示,并且只将字符串解析为datetime
对象以便':00'
在字符串末尾删除,您可以只删除最后 3 个字符:
>>> "2016-05-19 08:25:00"[:-3]
'2016-05-19 08:25'
You could apply this to every element in your list, before initializing df['start_date_time']
:
在初始化之前,您可以将其应用于列表中的每个元素df['start_date_time']
:
>>> start_date_time = ["2016-05-19 08:25:00","2016-05-19 16:00:00","2016-05-20 07:45:00","2016-05-24 12:50:00","2016-05-25 23:00:00","2016-05-26 19:45:00"]
>>> map(lambda s: s[:-3], start_date_time)
['2016-05-19 08:25', '2016-05-19 16:00', '2016-05-20 07:45', '2016-05-24 12:50', '2016-05-25 23:00', '2016-05-26 19:45']
Display datetimes without seconds
显示没有秒的日期时间
If you want to work with datetime
objects but don't want to show seconds :
如果您想处理datetime
对象但不想显示秒数:
print(df['start_date_time'].apply(lambda t: t.strftime('%Y-%m-%d %H:%M')))
# 0 2016-05-19 08:25
# 1 2016-05-19 16:00
# 2 2016-05-20 07:45
# 3 2016-05-24 12:50
# 4 2016-05-25 23:00
# 5 2016-05-26 19:45
# Name: start_date_time, dtype: object
回答by jahurul25
HTML Code:
HTML代码:
< input type="time" class="form-control" value="" name="meeting_time" required />
< input type="time" class="form-control" value="" name="meeting_time" required />
Python Django Code:
Python Django 代码:
meeting_time = request.POST['meeting_time'] #Like your_time = "12:35:00"
meeting_time = request.POST['meeting_time'] #Like your_time = "12:35:00"
get_time = meeting_time.strftime("%H:%M")
get_time = meeting_time.strftime("%H:%M")
Result is :
结果是:
get_time = "12:35"
get_time = "12:35"
回答by jahurul25
Give this a shot with:
试一试:
df.index = df.index.map(lambda t: t.strftime('%Y-%m-%d %H:%M'))
As written in one of the comments, the above apply to the case where the dates are not strings. If they, however, are strings, you can simply slice the last three characters from each list in the list:
正如其中一条评论中所写,上述内容适用于日期不是字符串的情况。但是,如果它们是字符串,则可以简单地将列表中每个列表的最后三个字符切片:
import pandas as pd
df = pd.DataFrame({'date': ["2016-05-19 08:25:00"]})
print(df['date'].map(lambda t: t[:-3]))
The above will output:
以上将输出:
0 2016-05-19 08:25 Name: date, dtype: object
0 2016-05-19 08:25 Name: date, dtype: object
回答by Flurin
You can subtract the seconds using a timedelta:
您可以使用 timedelta 减去秒数:
import datetime
d = datetime.datetime.now() #datetime including seconds
without_seconds = d - datetime.timedelta(seconds=d.second)
回答by M. Leung
Convert String to datetime object first, then you can use the replace method.
先将String转换为datetime对象,然后就可以使用replace方法了。
from _datetime import *
df = dict()
df['start_date_time'] = ["2016-05-19 08:25:00",
"2016-05-19 16:00:00",
"2016-05-20 07:45:00",
"2016-05-24 12:50:00",
"2016-05-25 23:00:00",
"2016-05-26 19:45:00"]
for dt in df['start_date_time']:
cur_dt = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
cur_dt = cur_dt.replace(second=0)
print(cur_dt)
cur_dt_without_second = cur_dt.strftime('%Y-%m-%d %H:%M')
print(cur_dt_without_second)
-------------------
2016-05-19 08:25:00
2016-05-19 08:25
2016-05-19 16:00:00
2016-05-19 16:00
2016-05-20 07:45:00
2016-05-20 07:45
2016-05-24 12:50:00
2016-05-24 12:50
2016-05-25 23:00:00
2016-05-25 23:00
2016-05-26 19:45:00
2016-05-26 19:45
回答by Rolf of Saxony
Convert the string to a datetime object and then manipulate that
将字符串转换为日期时间对象,然后对其进行操作
>>> x = ["2016-05-19 08:25:00","2016-05-19 16:00:00","2016-05-20 07:45:00","2016-05-24 12:50:00","2016-05-25 23:00:00","2016-05-26 19:45:00"]
>>> for i in x:
... y = datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S')
... z = datetime.datetime.strftime(y, '%Y-%m-%d %H:%M')
... print (y, type(y))
... print (z, type(z))
...
(datetime.datetime(2016, 5, 19, 8, 25), <type 'datetime.datetime'>)
('2016-05-19 08:25', <type 'str'>)
(datetime.datetime(2016, 5, 19, 16, 0), <type 'datetime.datetime'>)
('2016-05-19 16:00', <type 'str'>)
(datetime.datetime(2016, 5, 20, 7, 45), <type 'datetime.datetime'>)
('2016-05-20 07:45', <type 'str'>)
(datetime.datetime(2016, 5, 24, 12, 50), <type 'datetime.datetime'>)
('2016-05-24 12:50', <type 'str'>)
(datetime.datetime(2016, 5, 25, 23, 0), <type 'datetime.datetime'>)
('2016-05-25 23:00', <type 'str'>)
(datetime.datetime(2016, 5, 26, 19, 45), <type 'datetime.datetime'>)
('2016-05-26 19:45', <type 'str'>)
回答by Lyncean Patel
As you mentioned removed so I assumed you don't want the seconds or microsecond in the result.If this is the case then following might help:
正如您提到的那样,我假设您不希望结果中出现秒或微秒。如果是这种情况,那么以下内容可能会有所帮助:
datetime_variable.strftime("'%Y-%m-%d %H:%M'")
datetime_variable.strftime("'%Y-%m-%d %H:%M'")
If you have datetime in string then you can convert it in datetime obj:
如果字符串中有日期时间,则可以将其转换为日期时间对象:
from dateutil import parser
datetime_variable = parser.parse(str_datetime_var)
datetime_variable.strftime("'%Y-%m-%d %H:%M'")
from dateutil import parser
datetime_variable = parser.parse(str_datetime_var)
datetime_variable.strftime("'%Y-%m-%d %H:%M'")
回答by Monkeybike123
this is with the time module not datetime module but might be what your looking for...
这是时间模块而不是日期时间模块,但可能是您要找的...
import time
X = time.strftime("%H:%M")
print(X)
or you with seconds
或者你有秒
import time
X = time.strftime("%H:%M:%S")
print(X)
If your gonna down vote please explain why
如果您要投反对票,请解释原因