如何在Python中创建时间范围?

时间:2018-12-22 07:33:58

标签: python python-3.x pandas

我想遍历一个小时的值来绘制每小时的旅行次数。

我在互联网上找不到解决该问题的方法。可以告诉我该怎么做吗?

2 个答案:

答案 0 :(得分:2)

您可以在https://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html上找到最佳文档。

请看下面的例子。

>>> import pandas as pd
>>>
>>> times = pd.date_range("2018-01-01", freq = "s", periods = 5)
>>>
>>> d = {
...     'fullname': ["A X", "G Y", "K P", "T B", "R O"], "entry_time": times
... }
>>>
>>> df = pd.DataFrame(d)
>>> df
  fullname          entry_time
0      A X 2018-01-01 00:00:00
1      G Y 2018-01-01 00:00:01
2      K P 2018-01-01 00:00:02
3      T B 2018-01-01 00:00:03
4      R O 2018-01-01 00:00:04
>>>
>>> df["entry_time"]
0   2018-01-01 00:00:00
1   2018-01-01 00:00:01
2   2018-01-01 00:00:02
3   2018-01-01 00:00:03
4   2018-01-01 00:00:04
Name: entry_time, dtype: datetime64[ns]
>>>
>>> df["entry_time"][0]
Timestamp('2018-01-01 00:00:00')
>>>
>>> str(df["entry_time"][1].time())
'00:00:01'
>>>
>>> df["entry_time"][1].time()
datetime.time(0, 0, 1)
>>>
>>> df["entry_time"][1].year
2018
>>>
>>> for t in times:
...     print(t)
...
2018-01-01 00:00:00
2018-01-01 00:00:01
2018-01-01 00:00:02
2018-01-01 00:00:03
2018-01-01 00:00:04
>>>

这是列出Timestamp对象上定义的所有方法/属性的方法。

>>> dir(df["entry_time"][0])
['__add__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribut
e__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__pyx
_vtable__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__setstate__', '__sizeof__'
, '__str__', '__sub__', '__subclasshook__', '__weakref__', '_date_attributes', '_date_repr', '_get_date_name_field', '_get
_start_end_field', '_has_time_component', '_repr_base', '_round', '_short_repr', '_time_repr', 'asm8', 'astimezone', 'ceil
', 'combine', 'ctime', 'date', 'day', 'day_name', 'dayofweek', 'dayofyear', 'days_in_month', 'daysinmonth', 'dst', 'floor'
, 'fold', 'freq', 'freqstr', 'fromordinal', 'fromtimestamp', 'hour', 'is_leap_year', 'is_month_end', 'is_month_start', 'is
_quarter_end', 'is_quarter_start', 'is_year_end', 'is_year_start', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'micro
second', 'min', 'minute', 'month', 'month_name', 'nanosecond', 'normalize', 'now', 'quarter', 'replace', 'resolution', 'ro
und', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'to_datetime64', 'to_julian_date', 'to
_period', 'to_pydatetime', 'today', 'toordinal', 'tz', 'tz_convert', 'tz_localize', 'tzinfo', 'tzname', 'utcfromtimestamp'
, 'utcnow', 'utcoffset', 'utctimetuple', 'value', 'week', 'weekday', 'weekday_name', 'weekofyear', 'year']
>>>

答案 1 :(得分:1)

一个小时间隔时间产生了7天

dates = pd.date_range(start='2018-08-08', end = '2018-08-15', freq='H')

创建一个数据框并一个接一个地存储数据

df_new = pd.DataFrame(columns=['dates', 'generater_reading'])
df_new.dates = dates

您应该查看文档here 您还可以在此处创建任意数量的日期间隔和自定义时间跨度。 所有示例均可用,因此您可以进行遍历。