10 examples of 'convert pandas series to datetime' in Python

Every line of 'convert pandas series to datetime' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
112def get_is_daytime_from_series(series: pd.Series) -> pd.Series:
113 """Return if time in daytime interval."""
114 interval = DAY_INTERVAL
115 return get_time_is_in_interval_from_series(series,
116 start_time=interval[0],
117 end_time=interval[1])
30def converter(df: DataFrame) -> Series:
31 return df[field_name]
553def to_datetime(self, dayfirst=False):
554 """
555 DEPRECATED: use :meth:`to_timestamp` instead.
556
557 Cast to DatetimeIndex.
558 """
559 warnings.warn("to_datetime is deprecated. Use self.to_timestamp(...)",
560 FutureWarning, stacklevel=2)
561 return self.to_timestamp()
45def _is_datetime(s):
46 if is_datetime64_any_dtype(s):
47 return True
48 try:
49 if is_object_dtype(s):
50 pd.to_datetime(s, infer_datetime_format=True)
51 return True
52 except Exception: # pylint: disable=broad-except
53 pass
54 return False
322def to_timestamp(self, freq=None, how='start'):
323 """
324 Cast to DatetimeArray/Index.
325
326 Parameters
327 ----------
328 freq : string or DateOffset, optional
329 Target frequency. The default is 'D' for week or longer,
330 'S' otherwise
331 how : {'s', 'e', 'start', 'end'}
332
333 Returns
334 -------
335 DatetimeArray/Index
336 """
337 from pandas.core.arrays import DatetimeArray
338
339 how = libperiod._validate_end_alias(how)
340
341 end = how == 'E'
342 if end:
343 if freq == 'B':
344 # roll forward to ensure we land on B date
345 adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
346 return self.to_timestamp(how='start') + adjust
347 else:
348 adjust = Timedelta(1, 'ns')
349 return (self + self.freq).to_timestamp(how='start') - adjust
350
351 if freq is None:
352 base, mult = libfrequencies.get_freq_code(self.freq)
353 freq = libfrequencies.get_to_timestamp_base(base)
354 else:
355 freq = Period._maybe_convert_freq(freq)
356
357 base, mult = libfrequencies.get_freq_code(freq)
358 new_data = self.asfreq(freq, how=how)
359
360 new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
361 return DatetimeArray._from_sequence(new_data, freq='infer')
148def localize_datetime(x):
149 if pd.isnull(x) or isinstance(x, pd.tslib.NaTType):
150 return None
151 utz_tz = pytz.timezone('UTC')
152 local_tz = pytz.timezone(utc_to_tz)
153 d = utz_tz.localize(x)
154 d = d.astimezone(local_tz)
155 # make naive.
156 return d.replace(tzinfo=None)
302def to_pandas(self) -> None:
303 '''Return a Pandas Index.
304 '''
305 raise NotImplementedError('Pandas does not support a year month type, and it is ambiguous if a date proxy should be the first of the month or the last of the month.')
84def as_timestamp(obj):
85 if isinstance(obj, Timestamp):
86 return obj
87 try:
88 return Timestamp(obj)
89 except (OutOfBoundsDatetime):
90 pass
91 return obj
8def convert_to_datetime(datetime_str):
9 tweet_datetime = datetime.strptime(datetime_str,'%a %b %d %H:%M:%S %z %Y')
10
11 return(tweet_datetime)
20def datetime_to_seconds(arr):
21 """Convert an array of datetime64[ns] to seconds since the UNIX epoch"""
22
23 if arr.dtype != np.dtype('datetime64[ns]'):
24 if arr.dtype == 'int64':
25 # The user has passed a unix timestamp already
26 return arr
27 elif arr.dtype == 'object' or str(arr.dtype).startswith(
28 'datetime64[ns,'):
29 # Convert to datetime64[ns] from string
30 # Or from datetime with timezone information
31 # Return timestamp in 'UTC'
32 arr = pd.to_datetime(arr, utc=True)
33 else:
34 raise TypeError(f"Invalid dtype '{arr.dtype}', expected one of: "
35 "datetime64[ns], int64 (UNIX epoch), "
36 "or object (string)")
37 return arr.view('i8') // 10**9 # ns -> s since epoch

Related snippets