赞
踩
目录
286、pandas.Series.dt.to_pydatetime方法
287、pandas.Series.dt.tz_localize方法
288、pandas.Series.dt.tz_convert方法
289、pandas.Series.dt.normalize方法
290、pandas.Series.dt.strftime函数
- # 286、pandas.Series.dt.to_pydatetime方法
- pandas.Series.dt.to_pydatetime()
- Return the data as an array of datetime.datetime objects.
-
- Deprecated since version 2.1.0: The current behavior of dt.to_pydatetime is deprecated. In a future version this will return a Series containing python datetime objects instead of a ndarray.
-
- Timezone information is retained if present.
-
- Warning
-
- Python’s datetime uses microsecond resolution, which is lower than pandas (nanosecond). The values are truncated.
-
- Returns:
- numpy.ndarray
- Object dtype array containing native Python datetime objects.
无
将pandas.Series中的日期时间类型值(如Timestamp对象)转换为Python原生的datetime对象数组,该方法在以下几种情况下特别有用:
286-3-1、与其他库的兼容性:有些库或函数只接受Python原生的datetime对象,而不接受pandas.Timestamp对象,这时可以使用该方法进行转换。
286-3-2、日期时间处理:在进行日期时间运算或处理时,有时需要使用Python的内置日期时间处理功能,该方法可以简化这种转换过程。
286-3-3、数据传递:当需要将数据传递给仅支持Python原生datetime对象的外部系统或接口时,可以使用此方法进行转换。
返回一个numpy.ndarray,其中包含与原Series中的每个元素对应的datetime.datetime对象。换句话说,返回的数组中的每个元素都是原Series中Timestamp对象的Python原生datetime对象版本。
使用场景:
286-5-1、与其他库或函数的兼容性:许多库(如matplotlib、seaborn)和函数需要使用Python原生的datetime对象,而不是pandas的Timestamp对象。在这种情况下,可以使用to_pydatetime方法进行转换,从而确保兼容性。例如,在绘制时间序列图时,某些图形库可能只接受datetime对象。
286-5-2、日期时间处理:有时需要利用Python的内置日期时间处理功能来进行复杂的日期时间运算或处理,这些操作可能在datetime对象上更容易实现,因此可以先将pandas.Timestamp对象转换为datetime对象。例如,使用datetime的方法和属性(如weekday()、replace()等)进行特定的日期操作。
286-5-3、数据传递:当需要将数据传递给仅支持Python原生datetime对象的外部系统或接口时,可以使用该方法进行转换。例如,某些API或数据库接口只接受datetime对象,使用to_pydatetime方法可以确保数据格式的正确性。
286-5-4、调试和数据检查:在调试和数据检查过程中,有时需要查看或打印日期时间值的具体内容,使用datetime对象进行检查可能更直观,因为datetime对象的字符串表示形式比Timestamp对象更易读。
286-5-5、处理缺失数据:在处理缺失日期时间数据时,转换为datetime对象可以更方便地使用Python的原生方法进行处理。例如,可以利用datetime的min和max属性来处理缺失值。
无
- # 286、pandas.Series.dt.to_pydatetime方法
- # 286-1、使用matplotlib绘制时间序列图
- import pandas as pd
- import matplotlib.pyplot as plt
- # 创建包含日期时间值的Series
- date_series = pd.Series(pd.date_range('2024-05-01', periods=10, freq='D'))
- # 转换为Python datetime对象
- dates = date_series.dt.to_pydatetime()
- # 使用matplotlib绘制时间序列图
- plt.plot(dates, range(10))
- plt.xlabel('Date')
- plt.ylabel('Value')
- plt.title('Time Series Plot')
- # 让x轴的标签斜着显示
- plt.xticks(rotation=45)
- plt.show()
-
- # 286-2、使用原生datetime方法进行日期处理
- import pandas as pd
- # 创建包含日期时间值的Series
- date_series = pd.Series(pd.date_range('2024-07-01', periods=5, freq='D'))
- # 转换为Python datetime对象
- dates = date_series.dt.to_pydatetime()
- # 计算每个日期是星期几
- weekdays = [date.weekday() for date in dates]
- print(weekdays, end='\n\n')
-
- # 286-3、将数据传递给支持datetime的接口
- import pandas as pd
- # 创建包含日期时间值的Series
- date_series = pd.Series(pd.date_range('2024-08-01', periods=5, freq='D'))
- # 转换为Python datetime对象
- dates = date_series.dt.to_pydatetime()
- # 假设有一个只接受datetime对象的函数
- def process_dates(dates):
- for date in dates:
- print(f"Processing date: {date}")
-
- # 286-4、处理缺失数据
- import pandas as pd
- from datetime import datetime
- # 创建包含日期时间值和缺失值的Series
- date_series = pd.Series([pd.Timestamp('2024-01-01'), pd.NaT, pd.Timestamp('2024-01-03')])
- # 转换为Python datetime对象,并处理缺失值
- dates = date_series.dt.to_pydatetime()
- dates = [date if date is not pd.NaT else datetime.min for date in dates]
- print(dates, end='\n\n')
-
- # 286-5、与其他库兼容性
- import pandas as pd
- import seaborn as sns
- import matplotlib.pyplot as plt
- # 创建包含日期时间值的DataFrame
- df = pd.DataFrame({
- 'date': pd.date_range('2024-07-01', periods=10, freq='D'),
- 'value': range(10)
- })
- # 转换日期列为Python datetime对象
- df['date'] = df['date'].dt.to_pydatetime()
- # 使用 seaborn 绘制时间序列图
- sns.lineplot(x='date', y='value', data=df)
- plt.xlabel('Date')
- plt.ylabel('Value')
- plt.title('Time Series Plot with Seaborn')
- # 让x轴的标签斜着显示
- plt.xticks(rotation=45)
- plt.show()
- # 286、pandas.Series.dt.to_pydatetime方法
- # 286-1、使用matplotlib绘制时间序列图
- # 见图1
-
- # 286-2、使用原生datetime方法进行日期处理
- # [0, 1, 2, 3, 4]
-
- # 286-3、将数据传递给支持datetime的接口
- # Processing date: 2024-08-01 00:00:00
- # Processing date: 2024-08-02 00:00:00
- # Processing date: 2024-08-03 00:00:00
- # Processing date: 2024-08-04 00:00:00
- # Processing date: 2024-08-05 00:00:00
-
- # 286-4、处理缺失数据
- # [datetime.datetime(2024, 1, 1, 0, 0), datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(2024, 1, 3, 0, 0)]
-
- # 286-5、与其他库兼容性
- # 见图2
图1:
图2:
- # 287、pandas.Series.dt.tz_localize方法
- pandas.Series.dt.tz_localize(*args, **kwargs)
- Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index.
-
- This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another time zone.
-
- This method can also be used to do the inverse – to create a time zone unaware object from an aware object. To that end, pass tz=None.
-
- Parameters:
- tz
- str, pytz.timezone, dateutil.tz.tzfile, datetime.tzinfo or None
- Time zone to convert timestamps to. Passing None will remove the time zone information preserving local time.
-
- ambiguous
- ‘infer’, ‘NaT’, bool array, default ‘raise’
- When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the ambiguous parameter dictates how ambiguous times should be handled.
-
- ‘infer’ will attempt to infer fall dst-transition hours based on order
-
- bool-ndarray where True signifies a DST time, False signifies a non-DST time (note that this flag is only applicable for ambiguous times)
-
- ‘NaT’ will return NaT where there are ambiguous times
-
- ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
-
- nonexistent
- ‘shift_forward’, ‘shift_backward, ‘NaT’, timedelta, default ‘raise’
- A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
-
- ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
-
- ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
-
- ‘NaT’ will return NaT where there are nonexistent times
-
- timedelta objects will shift nonexistent times by the timedelta
-
- ‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
-
- Returns:
- Same type as self
- Array/Index converted to the specified time zone.
-
- Raises:
- TypeError
- If the Datetime Array/Index is tz-aware and tz is not None.
287-2-1、*args(可选):其他位置参数,为后续扩展功能做预留。
287-2-2、**kwargs(可选):其他关键字参数,具体包括以下参数:
287-2-2-1、tz(可选,默认值为None):字符串或pytz.timezone对象,指定要设置的时区,当传入None时,会移除现有的时区信息。
287-2-2-2、axis(可选,默认值为0):整数或字符串,指定应用于行还是列。
287-2-2-3、level(可选,默认值为0):整数或名称,在MultiIndex场景下,指定要本地化的索引级别。
287-2-2-4、copy(可选,默认值为True):布尔值,是否返回一个新的对象,如果为True,返回一个新的对象;如果为False,在原对象上进行操作。
287-2-2-5、ambiguous(可选,默认值为'raise'):字符串或布尔型ndarray,处理夏令时(DST)变化期间的模糊时间,选项有:
287-2-2-6、nonexistent(可选,默认值为'raise'):字符串,处理夏令时变化期间不存在的时间,选项有:
将一个时间序列(datetime Series)本地化到指定的时区(timezone)。具体来说,它可以将一个“天真时间”(naive datetime,即没有时区信息的时间)或已有时区信息的时间序列转换为具有指定时区的时间序列。
返回一个新的时间序列,这个序列中的每个时间点都包含了指定的时区信息,返回的时间序列类型为pandas.Series,其元素为pandas.Timestamp对象,这些对象具有时区信息。
无
无
- # 287、pandas.Series.dt.tz_localize方法
- # 287-1、时区本地化
- import pandas as pd
- # 创建没有时区信息的时间序列
- naive_series = pd.Series(pd.date_range('2024-08-01', periods=3, freq='D'))
- # 打印原始数据
- print("原始时间序列:")
- print(naive_series)
- # 将时间序列本地化到UTC时区
- localized_series = naive_series.dt.tz_localize('UTC')
- # 打印本地化后的时间序列
- print("本地化到UTC时区后的时间序列:")
- print(localized_series, end='\n\n')
-
- # 287-2、数据一致性
- import pandas as pd
- # 创建两个不同的时间序列,分别在不同的时区
- series1 = pd.Series(pd.date_range('2024-08-01', periods=3, freq='D', tz='UTC'))
- series2 = pd.Series(pd.date_range('2024-08-01', periods=3, freq='D', tz='Asia/Kolkata'))
- # 打印原始数据
- print("不同来源的时间序列:")
- print("Series 1(UTC):")
- print(series1)
- print("Series 2(Asia/Kolkata):")
- print(series2)
- # 将所有数据转换到UTC时区
- series2 = series2.dt.tz_convert('UTC')
- # 打印转换后的时间序列
- print("转换到UTC时区后的时间序列:")
- print(series2, end='\n\n')
-
- # 287-3、夏令时处理
- import pandas as pd
- # 创建一个包含夏令时变化的时间序列
- dst_series = pd.Series(pd.date_range('2024-03-13 01:00', periods=3, freq='h'))
- # 打印原始数据
- print("包含夏令时变化的原始时间序列:")
- print(dst_series)
- # 处理夏令时模糊时间
- localized_dst_series = dst_series.dt.tz_localize('US/Eastern', ambiguous='shift_forward')
- # 打印处理后的时间序列
- print("处理夏令时模糊时间后的时间序列(shift_forward):")
- print(localized_dst_series)
- # 处理夏令时不存在的时间
- localized_nonexistent_series = dst_series.dt.tz_localize('US/Eastern', nonexistent='shift_forward')
- # 打印处理后的时间序列
- print("处理夏令时不存在时间后的时间序列(shift_forward):")
- print(localized_nonexistent_series, end='\n\n')
-
- # 287-4、数据转换和展示
- import pandas as pd
- # 创建在UTC时区的时间序列
- utc_series = pd.Series(pd.date_range('2024-08-01', periods=3, freq='D', tz='UTC'))
- # 打印原始数据
- print("UTC时区的原始时间序列:")
- print(utc_series)
- # 转换到用户所在的时区(America/New_York)
- user_tz_series = utc_series.dt.tz_convert('America/New_York')
- # 打印转换后的时间序列
- print("转换到用户所在时区(America/New_York)后的时间序列:")
- print(user_tz_series, end='\n\n')
-
- # 287-5、数据存储和传输
- import pandas as pd
- # 创建没有时区信息的时间序列
- naive_series = pd.Series(pd.date_range('2024-08-01', periods=3, freq='D'))
- # 将时间序列本地化到UTC时区用于存储
- store_series = naive_series.dt.tz_localize('UTC')
- # 打印存储的时间序列
- print("本地化到UTC时区以存储的时间序列:")
- print(store_series)
- # 读取数据后转换到本地时区(Asia/Shanghai)
- local_series = store_series.dt.tz_convert('Asia/Shanghai')
- # 打印转换后的时间序列
- print("转换到本地时区(Asia/Shanghai)后的时间序列:")
- print(local_series)
- # 287、pandas.Series.dt.tz_localize方法
- # 287-1、时区本地化
- # 原始时间序列:
- # 0 2024-08-01
- # 1 2024-08-02
- # 2 2024-08-03
- # dtype: datetime64[ns]
- # 本地化到UTC时区后的时间序列:
- # 0 2024-08-01 00:00:00+00:00
- # 1 2024-08-02 00:00:00+00:00
- # 2 2024-08-03 00:00:00+00:00
- # dtype: datetime64[ns, UTC]
-
- # 287-2、数据一致性
- # 不同来源的时间序列:
- # Series 1(UTC):
- # 0 2024-08-01 00:00:00+00:00
- # 1 2024-08-02 00:00:00+00:00
- # 2 2024-08-03 00:00:00+00:00
- # dtype: datetime64[ns, UTC]
- # Series 2(Asia/Kolkata):
- # 0 2024-08-01 00:00:00+05:30
- # 1 2024-08-02 00:00:00+05:30
- # 2 2024-08-03 00:00:00+05:30
- # dtype: datetime64[ns, Asia/Kolkata]
- # 转换到UTC时区后的时间序列:
- # 0 2024-07-31 18:30:00+00:00
- # 1 2024-08-01 18:30:00+00:00
- # 2 2024-08-02 18:30:00+00:00
- # dtype: datetime64[ns, UTC]
-
- # 287-3、夏令时处理
- # 包含夏令时变化的原始时间序列:
- # 0 2024-03-13 01:00:00
- # 1 2024-03-13 02:00:00
- # 2 2024-03-13 03:00:00
- # dtype: datetime64[ns]
- # 处理夏令时模糊时间后的时间序列(shift_forward):
- # 0 2024-03-13 01:00:00-04:00
- # 1 2024-03-13 02:00:00-04:00
- # 2 2024-03-13 03:00:00-04:00
- # dtype: datetime64[ns, US/Eastern]
- # 处理夏令时不存在时间后的时间序列(shift_forward):
- # 0 2024-03-13 01:00:00-04:00
- # 1 2024-03-13 02:00:00-04:00
- # 2 2024-03-13 03:00:00-04:00
- # dtype: datetime64[ns, US/Eastern]
-
- # 287-4、数据转换和展示
- # UTC时区的原始时间序列:
- # 0 2024-08-01 00:00:00+00:00
- # 1 2024-08-02 00:00:00+00:00
- # 2 2024-08-03 00:00:00+00:00
- # dtype: datetime64[ns, UTC]
- # 转换到用户所在时区(America/New_York)后的时间序列:
- # 0 2024-07-31 20:00:00-04:00
- # 1 2024-08-01 20:00:00-04:00
- # 2 2024-08-02 20:00:00-04:00
- # dtype: datetime64[ns, America/New_York]
-
- # 287-5、数据存储和传输
- # 本地化到UTC时区以存储的时间序列:
- # 0 2024-08-01 00:00:00+00:00
- # 1 2024-08-02 00:00:00+00:00
- # 2 2024-08-03 00:00:00+00:00
- # dtype: datetime64[ns, UTC]
- # 转换到本地时区(Asia/Shanghai)后的时间序列:
- # 0 2024-08-01 08:00:00+08:00
- # 1 2024-08-02 08:00:00+08:00
- # 2 2024-08-03 08:00:00+08:00
- # dtype: datetime64[ns, Asia/Shanghai]
- # 288、pandas.Series.dt.tz_convert方法
- pandas.Series.dt.tz_convert(*args, **kwargs)
- Convert tz-aware Datetime Array/Index from one time zone to another.
-
- Parameters:
- tz
- str, pytz.timezone, dateutil.tz.tzfile, datetime.tzinfo or None
- Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A tz of None will convert to UTC and remove the timezone information.
-
- Returns:
- Array or Index
- Raises:
- TypeError
- If Datetime Array/Index is tz-naive.
288-2-1、tz(必须):指定目标时区,可以是字符串(例如'US/Eastern','Europe/London'),也可以是pytz或者dateutil.tz模块中的时区对象。
288-2-2、axis(可选,默认值为0):在Series对象上无效,仅用于DataFrame对象。
288-2-3、level(可选,默认值为None):如果索引中有多级索引,则可以指定要转换时区的级别,此参数在Series中通常不使用。
288-2-4、copy(可选,默认值为True):是否复制底层数据,如果设置为False,则会就地修改现有数据,而不是创建数据的副本。
用于将datetime数据从一种时区转换到另一种时区的方法。
返回值是一个新的pandas.Series对象,包含转换到目标时区的时间戳。
使用场景:
288-5-1、数据标准化和统一:在处理来自不同时区的数据时,使用该方法可以将所有时间戳转换到同一时区,方便后续的数据分析和比较。
288-5-2、时间序列分析:在进行时间序列分析时,确保所有时间戳在同一时区可以避免因时区差异引起的误差,尤其是在计算统计量或绘制图表时。
288-5-3、日志文件处理:在分析服务器日志文件时,不同服务器可能位于不同的时区,通过该方法将时间戳统一转换到同一时区,可以更容易地进行统一分析和排查问题。
288-5-4、金融数据分析:金融市场的数据常常涉及多个时区,例如纽约(EST)、伦敦(GMT)和东京(JST),使用该方法可以将数据转换到交易时区,从而准确分析交易行为。
288-5-5、多时区日程安排:在处理跨时区的会议和日程安排时,可以使用该方法将所有时间戳转换到参与者的本地时区,确保时间安排准确无误。
无
- # 288、pandas.Series.dt.tz_convert方法
- # 288-1、数据标准化和统一
- import pandas as pd
- # 创建包含不同时区的时间序列数据
- data = {
- 'datetime': ['2024-01-01 09:30:00', '2024-01-01 13:00:00', '2024-01-01 18:00:00'],
- 'price': [100, 102, 105]
- }
- df = pd.DataFrame(data)
- df['datetime'] = pd.to_datetime(df['datetime'])
- # 假设这些时间戳来自不同的时区
- df['datetime'] = df['datetime'].dt.tz_localize('US/Eastern')
- # 将时间戳转换为UTC
- df['datetime_utc'] = df['datetime'].dt.tz_convert('UTC')
- print(df, end='\n\n')
-
- # 288-2、时间序列分析
- import pandas as pd
- # 创建时间序列数据
- data = {
- 'datetime': ['2024-01-01 09:30:00', '2024-01-01 10:00:00', '2024-01-01 15:00:00'],
- 'price': [100, 102, 105]
- }
- df = pd.DataFrame(data)
- df['datetime'] = pd.to_datetime(df['datetime'])
- # 假设这些时间戳是纽约时间(Eastern Time)
- df['datetime'] = df['datetime'].dt.tz_localize('US/Eastern')
- # 将时间戳转换为伦敦时间(GMT)
- df['datetime_gmt'] = df['datetime'].dt.tz_convert('Europe/London')
- print(df, end='\n\n')
-
- # 288-3、日志文件处理
- import pandas as pd
- # 创建日志数据
- data = {
- 'timestamp': ['2024-01-01 01:00:00', '2024-01-01 04:00:00', '2024-01-01 07:00:00'],
- 'event': ['start', 'process', 'end']
- }
- df = pd.DataFrame(data)
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- # 假设这些时间戳是UTC
- df['timestamp'] = df['timestamp'].dt.tz_localize('UTC')
- # 将时间戳转换为服务器本地时间(假设为美国太平洋时间)
- df['timestamp_pacific'] = df['timestamp'].dt.tz_convert('US/Pacific')
- print(df, end='\n\n')
-
- # 288-4、金融数据分析
- import pandas as pd
- # 创建金融市场数据
- data = {
- 'trade_time': ['2024-01-01 09:30:00', '2024-01-01 10:00:00', '2024-01-01 15:00:00'],
- 'price': [100, 102, 105]
- }
- df = pd.DataFrame(data)
- df['trade_time'] = pd.to_datetime(df['trade_time'])
- # 假设这些时间戳是东京时间(JST)
- df['trade_time'] = df['trade_time'].dt.tz_localize('Asia/Tokyo')
- # 将时间戳转换为纽约时间(Eastern Time)
- df['trade_time_eastern'] = df['trade_time'].dt.tz_convert('US/Eastern')
- print(df, end='\n\n')
-
- # 288-5、多时区日程安排
- import pandas as pd
- # 创建会议安排数据
- data = {
- 'meeting_time': ['2024-01-01 10:00:00', '2024-01-01 14:00:00', '2024-01-01 20:00:00'],
- 'agenda': ['Project Update', 'Team Meeting', 'Client Call']
- }
- df = pd.DataFrame(data)
- df['meeting_time'] = pd.to_datetime(df['meeting_time'])
- # 假设这些时间戳是伦敦时间(GMT)
- df['meeting_time'] = df['meeting_time'].dt.tz_localize('Europe/London')
- # 将时间戳转换为参与者的本地时区(假设为印度标准时间 IST)
- df['meeting_time_ist'] = df['meeting_time'].dt.tz_convert('Asia/Kolkata')
- print(df, end='\n\n')
-
- # 288-6、股票价格时间序列可视化
- import pandas as pd
- import matplotlib.pyplot as plt
- # 创建包含不同时区的时间序列数据
- data = {
- 'datetime': ['2024-01-01 09:30:00', '2024-01-01 13:00:00', '2024-01-01 18:00:00'],
- 'price': [100, 102, 105]
- }
- df = pd.DataFrame(data)
- df['datetime'] = pd.to_datetime(df['datetime'])
- # 假设这些时间戳来自不同的时区
- df['datetime'] = df['datetime'].dt.tz_localize('US/Eastern')
- # 将时间戳转换为 UTC
- df['datetime_utc'] = df['datetime'].dt.tz_convert('UTC')
- # 绘制时间序列图
- plt.figure(figsize=(10, 6))
- plt.plot(df['datetime_utc'], df['price'], marker='o', linestyle='-', color='b')
- plt.title('Stock Prices Over Time (UTC)')
- plt.xlabel('Time (UTC)')
- plt.ylabel('Price')
- plt.grid(True)
- plt.xticks(rotation=45)
- plt.tight_layout()
- plt.show()
- # 288、pandas.Series.dt.tz_convert方法
- # 288-1、数据标准化和统一
- # datetime price datetime_utc
- # 0 2024-01-01 09:30:00-05:00 100 2024-01-01 14:30:00+00:00
- # 1 2024-01-01 13:00:00-05:00 102 2024-01-01 18:00:00+00:00
- # 2 2024-01-01 18:00:00-05:00 105 2024-01-01 23:00:00+00:00
-
- # 288-2、时间序列分析
- # datetime price datetime_gmt
- # 0 2024-01-01 09:30:00-05:00 100 2024-01-01 14:30:00+00:00
- # 1 2024-01-01 10:00:00-05:00 102 2024-01-01 15:00:00+00:00
- # 2 2024-01-01 15:00:00-05:00 105 2024-01-01 20:00:00+00:00
-
- # 288-3、日志文件处理
- # timestamp event timestamp_pacific
- # 0 2024-01-01 01:00:00+00:00 start 2023-12-31 17:00:00-08:00
- # 1 2024-01-01 04:00:00+00:00 process 2023-12-31 20:00:00-08:00
- # 2 2024-01-01 07:00:00+00:00 end 2023-12-31 23:00:00-08:00
-
- # 288-4、金融数据分析
- # trade_time price trade_time_eastern
- # 0 2024-01-01 09:30:00+09:00 100 2023-12-31 19:30:00-05:00
- # 1 2024-01-01 10:00:00+09:00 102 2023-12-31 20:00:00-05:00
- # 2 2024-01-01 15:00:00+09:00 105 2024-01-01 01:00:00-05:00
-
- # 288-5、多时区日程安排
- # meeting_time agenda meeting_time_ist
- # 0 2024-01-01 10:00:00+00:00 Project Update 2024-01-01 15:30:00+05:30
- # 1 2024-01-01 14:00:00+00:00 Team Meeting 2024-01-01 19:30:00+05:30
- # 2 2024-01-01 20:00:00+00:00 Client Call 2024-01-02 01:30:00+05:30
-
- # 288-6、股票价格时间序列可视化
- # 见图3
-
图3:
- # 289、pandas.Series.dt.normalize方法
- pandas.Series.dt.normalize(*args, **kwargs)
- Convert times to midnight.
-
- The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected.
-
- This method is available on Series with datetime values under the .dt accessor, and directly on Datetime Array/Index.
-
- Returns:
- DatetimeArray, DatetimeIndex or Series
- The same type as the original data. Series will have the same name and index. DatetimeIndex will have the same name.
289-2-1、*args(可选):其他位置参数,为后续扩展功能做预留。
289-2-2、**kwargs(可选):其他关键字参数,为后续扩展功能做预留。
用于将带有时间信息的时间戳序列转换为只有日期的时间戳,即将所有时间部分设为午夜 (00:00:00),但保留时区信息(如果有的话)。
返回一个新的pandas.Series对象,其中每个时间戳的时间部分被归零,只保留日期部分。
使用场景:
289-5-1、数据聚合:当需要对数据按天进行聚合时,该方法可以将时间部分归零,使得不同时间的记录可以被归类到同一天进行统计。
289-5-2、时间序列对齐:在对齐两个不同时间戳的时间序列时,如果只关心日期部分,可以使用该方法将它们对齐到同一天。
289-5-3、数据筛选:当需要筛选出某一天的所有记录时,可以先将时间部分归零,然后根据日期进行筛选。
289-5-4、可视化:在进行时间序列数据的可视化时,有时只需要按天显示数据,可以使用该方法将时间部分去掉。
289-5-5、数据清洗:在数据清洗过程中,可能需要统一数据的时间部分,例如去除错误或不一致的时间信息,只保留日期部分。
无
- # 289、pandas.Series.dt.normalize方法
- # 289-1、数据聚合
- import pandas as pd
- # 示例数据
- data = {'timestamp': ['2024-01-01 09:30:00', '2024-01-01 15:45:00', '2024-01-02 10:00:00'],
- 'value': [10, 20, 30]}
- df = pd.DataFrame(data)
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- # 将时间归零
- df['date'] = df['timestamp'].dt.normalize()
- # 按日期聚合
- daily_sum = df.groupby('date')['value'].sum()
- print(daily_sum, end='\n\n')
-
- # 289-2、时间序列对齐
- import pandas as pd
- # 创建两个时间序列
- series1 = pd.Series([1, 2, 3], index=pd.date_range('2024-01-01 09:00', periods=3, freq='h'))
- series2 = pd.Series([4, 5, 6], index=pd.date_range('2024-01-01 10:00', periods=3, freq='h'))
- # 将时间归零
- series1.index = series1.index.normalize()
- series2.index = series2.index.normalize()
- # 对齐操作
- aligned_series = series1 + series2
- print(aligned_series, end='\n\n')
-
- # 289-3、数据筛选
- import pandas as pd
- # 示例数据
- data = {'timestamp': ['2024-01-01 09:30:00', '2024-01-01 15:45:00', '2024-01-02 10:00:00'],
- 'value': [10, 20, 30]}
- df = pd.DataFrame(data)
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- # 将时间归零
- df['date'] = df['timestamp'].dt.normalize()
- # 筛选特定日期的记录
- specific_date_records = df[df['date'] == '2024-01-01']
- print(specific_date_records, end='\n\n')
-
- # 289-4、可视化
- import pandas as pd
- import matplotlib.pyplot as plt
- # 示例数据
- data = {'timestamp': pd.date_range('2024-01-01', periods=100, freq='h'),
- 'value': range(100)}
- df = pd.DataFrame(data)
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- # 将时间归零
- df['date'] = df['timestamp'].dt.normalize()
- # 按日期聚合
- daily_data = df.groupby('date')['value'].mean()
- # 可视化
- daily_data.plot(kind='bar', color='purple')
- plt.xticks(rotation=15)
- plt.show()
-
- # 289-5、数据清洗
- import pandas as pd
- # 示例数据
- data = {'timestamp': ['2024-01-01 09:30:00', '2024-01-01 15:45:00', '2024-01-02 10:00:00'],
- 'value': [10, 20, 30]}
- df = pd.DataFrame(data)
- df['timestamp'] = pd.to_datetime(df['timestamp'])
- # 将时间归零,清洗数据
- df['timestamp'] = df['timestamp'].dt.normalize()
- print(df)
- # 289、pandas.Series.dt.normalize方法
- # 289-1、数据聚合
- # date
- # 2024-01-01 30
- # 2024-01-02 30
- # Name: value, dtype: int64
-
- # 289-2、时间序列对齐
- # 2024-01-01 5
- # 2024-01-01 7
- # 2024-01-01 9
- # dtype: int64
-
- # 289-3、数据筛选
- # timestamp value date
- # 0 2024-01-01 09:30:00 10 2024-01-01
- # 1 2024-01-01 15:45:00 20 2024-01-01
-
- # 289-4、可视化
- # 见图4
-
- # 289-5、数据清洗
- # timestamp value
- # 0 2024-01-01 10
- # 1 2024-01-01 20
- # 2 2024-01-02 30
图4:
- # 290、pandas.Series.dt.strftime函数
- pandas.Series.dt.strftime(*args, **kwargs)
- Convert to Index using specified date_format.
-
- Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in python string format doc.
-
- Formats supported by the C strftime API but not by the python string format doc (such as “%R”, “%r”) are not officially supported and should be preferably replaced with their supported equivalents (such as “%H:%M”, “%I:%M:%S %p”).
-
- Note that PeriodIndex support additional directives, detailed in Period.strftime.
-
- Parameters:
- date_format
- str
- Date format string (e.g. “%Y-%m-%d”).
-
- Returns:
- ndarray[object]
- NumPy ndarray of formatted strings.
format(必须):指定datetime对象应表示为字符串的格式,格式代码类似于Python内置的datetime.strftime函数,格式代码详情如下:
用于将pandas系列中的datetime对象转换为格式化的字符串,该函数在需要以特定格式表示日期和时间信息用于报告或展示时特别有用。
返回一个新的pandas系列,其中包含根据指定格式表示的格式化日期和时间值的字符串。
使用场景:
290-5-1、日志记录:在记录日志时,需要精确记录事件发生的时间,通过strftime可以将时间戳格式化为标准化的日志记录格式。
290-5-2、数据导出:在导出数据时,通常需要将日期和时间格式化为可读性强且标准化的形式,以便在Excel或其他工具中查看。
290-5-3、Web应用展示:在Web应用中,需要将后台的日期时间数据转换为用户友好的格式进行展示。
290-5-4、文件命名:在创建文件时,可以使用当前时间作为文件名的一部分,以避免命名冲突。
290-5-5、用户输入解析:在处理用户输入的日期时间时,需要将字符串解析为日期对象进行计算或比较,同时也需要将结果格式化为用户可读的形式。
290-5-6、自动化报告:在生成自动化报告时,通常需要在报告中包含生成时间,以便追踪报告的生成日期。
无
- # 290、pandas.Series.dt.strftime函数
- # 290-1、日志记录
- import logging
- from datetime import datetime
- logging.basicConfig(level=logging.INFO)
- now = datetime.now()
- formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
- logging.info(f'Event occurred at {formatted_time}')
-
- # 290-2、数据导出
- import pandas as pd
- data = {'timestamp': pd.to_datetime(['2024-08-07 14:30:59', '2024-12-25 09:15:00'])}
- df = pd.DataFrame(data)
- df['formatted_date'] = df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
- df.to_csv('exported_data.csv', index=False)
-
- # 290-3、Web应用展示
- from flask import Flask, render_template_string
- from datetime import datetime
- app = Flask(__name__)
- @app.route('/')
- def index():
- now = datetime.now()
- formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
- return render_template_string('<p>Current time: {{ time }}</p>', time=formatted_time)
- if __name__ == '__main__':
- app.run()
-
- # 290-4、文件命名
- from datetime import datetime
- now = datetime.now()
- formatted_time = now.strftime('%Y%m%d_%H%M%S')
- filename = f'backup_{formatted_time}.zip'
- print(filename)
-
- # 290-5、用户输入解析
- from datetime import datetime
- user_input = '2024-08-07 14:30:59'
- parsed_date = datetime.strptime(user_input, '%Y-%m-%d %H:%M:%S')
- formatted_date = parsed_date.strftime('%B %d, %Y at %I:%M %p')
- print(formatted_date)
-
- # 290-6、自动化报告
- from datetime import datetime
- now = datetime.now()
- formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
- report_content = f'Report generated on {formatted_time}\n...'
- with open('report.txt', 'w') as file:
- file.write(report_content)
- # 290、pandas.Series.dt.strftime函数
- # 输出结果类似于:
- # INFO:root:Event occurred at 2024-08-07 21:10:26
- # INFO:numexpr.utils:NumExpr defaulting to 4 threads.
- # * Serving Flask app 'test1'
- # * Debug mode: off
- # INFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
- # * Running on http://127.0.0.1:5000
- # INFO:werkzeug:Press CTRL+C to quit
- # backup_20240807_211032.zip
- # August 07, 2024 at 02:30 PM
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。