10 examples of 'object to datetime pandas' in Python

Every line of 'object to datetime pandas' 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
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.')
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()
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)
30def converter(df: DataFrame) -> Series:
31 return df[field_name]
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
80def to_datetime(obj):
81 """Convert `obj` into a `datetime` object.
82
83 * If `obj` is a `datetime` object it is returned untouched.
84 * if `obj` is None the current time in UTC is used.
85 * if `obj` is a `date` object it will be converted into a `datetime` object.
86 * if `obj` is a number it is interpreted as a timestamp.
87
88 Note: All values are localized to the users timezone.
89 Never use this for calculations, only for presentation!
90 """
91 if obj is None:
92 dt = datetime.utcnow()
93 elif isinstance(obj, datetime):
94 dt = obj
95 elif isinstance(obj, date):
96 dt = datetime(obj.year, obj.month, obj.day)
97 elif isinstance(obj, (int, long, float)):
98 dt = datetime.fromtimestamp(obj)
99 else:
100 raise TypeError('expecting datetime, date int, long, float, or None; '
101 'got %s' % type(obj))
102 return rebase_to_timezone(dt)
18@classmethod
19def to_datetime(cls, obj, end_of_year=False):
20 """Create datetime object from the inputted object."""
21 if isinstance(obj, bool):
22 return obj
23 if isinstance(obj, datetime.datetime):
24 return obj
25 if isinstance(obj, int):
26 if end_of_year:
27 month, day = 12, 31
28 else:
29 month, day = 1, 1
30 return datetime.datetime(obj, month, day)
31 if isinstance(obj, str):
32 return cls.str_to_datetime(obj)
33 try:
34 return datetime.datetime(obj)
35 except:
36 raise
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
33def datesarray_to_datetimearray(dates: np.ndarray) -> np.ndarray:
34 """
35 Convert an pandas-array of timestamps into
36 An numpy-array of datetimes
37 :return: numpy-array of datetime
38 """
39 return dates.dt.to_pydatetime()
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')

Related snippets