10 examples of 'convert object to datetime python' in Python

Every line of 'convert object to datetime python' 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
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)
32def datetime(obj, utc=False):
33 if obj is None:
34 return None
35 elif isinstance(obj, builtin_datetime.date):
36 return obj
37 elif isinstance(obj, basestring):
38 return parse(obj, utc=utc)
39 else:
40 raise ValueError("Can only convert strings into dates, received {}".format(obj.__class__))
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)
271@encoder.register(datetime.datetime)
272def encode_datetime(obj):
273 return {"ISO8601_datetime": obj.strftime("%Y-%m-%dT%H:%M:%S.%f%z")}
263def pyCalendarToSQLTimestamp(pydt):
264
265 if pydt.isDateOnly():
266 return date(year=pydt.getYear(), month=pydt.getMonth(), day=pydt.getDay())
267 else:
268 return datetime(
269 year=pydt.getYear(),
270 month=pydt.getMonth(),
271 day=pydt.getDay(),
272 hour=pydt.getHours(),
273 minute=pydt.getMinutes(),
274 second=pydt.getSeconds(),
275 tzinfo=None
276 )
11def to_datetime(date_str: str) -> datetime:
12 d = date_str
13 try:
14 dte = datetime.strptime(d, "%Y-%m")
15 except ValueError:
16 dte = date_str
17 return dte
39def convert_date(date):
40 return datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ")
25def to_dict(self, value):
26 if value is None:
27 return value
28 return dt_to_timestamp(value)
47def datetime_obj(*args, **kwargs):
48 return datetime.datetime(*args, **kwargs)
82def str_to_dt(date):
83 ''' Converts Yahoo Date Strings to datetime objects. '''
84 yr = int(date[0:4])
85 mo = int(date[5:7])
86 day = int(date[8:10])
87 return datetime.datetime(yr,mo, day)

Related snippets