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

Every line of 'convert string to datetime in 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
this disclaimer
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)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

43def convert_datetime(s):
44 """
45 Convert a datetime string to a standard format
46 """
47 try:
48 dt = DateTimeFromString(s)
49 date_string = dt.Format("%m/%d/%Y %H:%M:%S")
50 return date_string
51 except:
52 return s
98def string_to_datetime(string):
99 """
100 Takes a string formatted as follows yyyymmddhhmmss and returns a datetime.datetime object.
101 """
102 year=int(string[0:4])
103 month=int(string[4:6])
104 day=int(string[6:8])
105 hour=int(string[8:10])
106 min=int(string[10:12])
107 sec=int(string[12:14])
108
109 return datetime.datetime(year,month,day,hour,min,sec)
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
5def parse_datetime(datetime_str):
6 if datetime_str:
7 return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M')
26def to_datetime(string):
27 """Load UTC time as a string into a datetime object."""
28 try:
29 # Format is 2011-07-05 01:26:12.084316
30 return datetime.datetime.strptime(
31 string.split('.', 1)[0], '%Y-%m-%d %H:%M:%S')
32 except ValueError:
33 return datetime.datetime.strptime(string, '%Y-%m-%d')
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)
23def _datetime_deserialize(s):
24 return datetime.datetime.strptime(s, _datetime_format)
181def mk_datetime(string):
182 return datetime.datetime.fromtimestamp(time.mktime(email.utils.parsedate(string)))
70def test_string_to_datetime(self):
71 result = self.converter.string_to_datetime(self.test_date_string, '%d/%m/%Y', '%Y-%d-%m')
72 self.assertEquals(datetime, type(result))
73 self.assertEquals(self.expected_year, result.year)
74 self.assertEquals(self.expected_month, result.month)
75 self.assertEquals(self.expected_day, result.day)
76
77 result = self.converter.string_to_datetime(self.test_date_string, '%d/%m/%Y')
78 self.assertEquals(datetime, type(result))
79 self.assertEquals(self.expected_year, result.year)
80 self.assertEquals(self.expected_month, result.month)
81 self.assertEquals(self.expected_day, result.day)

Related snippets