Sign in Welcome! Log into your account your username your password Forgot your password? Get help Password recovery Recover your password your email A password will be e-mailed to you. HomeProgrammingChanging Strings to datetime in Python Programming Changing Strings to datetime in Python By Admin December 1, 2022 0 2 Share FacebookTwitterPinterestWhatsApp Introduction Knowledge may be represented in numerous varieties – and a convinient strategy to signify dates and occasions are strings. Nonetheless, to work with these dates and occasions in an arhithmetic style (akin to calculating time variations, including or eradicating time, and many others.) – we have to convert them to a datetime object. One of the crucial widespread sources of string-formatted datetimes are REST APIs that return agnostic strings, that we are able to then convert to different codecs. Moreover – timezones are a standard headache with regards to working with datetime objects, so we’ll want to consider that whereas changing too. On this information – we’ll check out tips on how to convert a string date/time right into a datetime object in Python, utilizing the built-in datetime module, but additionally third-party modules akin to dateutil, arrow and Maya, accounting for timezones. Changing Strings Utilizing datetime The datetime module consists of three totally different object sorts: date, time, and datetime. The date object holds the date, time holds the time, and datetime holds each date and time! import datetime print(f'Present date/time: {datetime.datetime.now()}') Working this code would end in: Present date/time: 2022-12-01 10:27:03.929149 When no customized formatting is given, the default string format is used, i.e. the format for “2022-12-01 10:27:03.929149” is in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.mmmmmm). If our enter string to create a datetime object is in the identical ISO 8601 format or if you recognize the format you will be receiving upfront, we are able to simply parse it to a datetime object: import datetime date_time_str = '2022-12-01 10:27:03.929149' date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f') print('Date:', date_time_obj.date()) print('Time:', date_time_obj.time()) print('Date-time:', date_time_obj) Working it is going to print the date, time, and date-time: Date: 2022-12-01 Time: 10:27:03.929149 Date-time: 2022-12-01 10:27:03.929149 Right here, we use the strptime() technique, which accepts two arguments: The string-formatted date The format of the primary argument Specifying the format like this makes the parsing a lot sooner since datetime does not must try to interpret the format by itself, which is far more costly computationally. The return worth is of the sort datetime. In our instance, "2022-12-01 10:27:03.929149" is the enter string and "%Y-%m-%d %H:%M:%S.%f" is the format of our date string. The returned datetime worth is saved as date_time_obj. Since this can be a datetime object, we are able to name the date() and time() strategies immediately on it. As you may see from the output, it prints the ‘date’ and ‘time’ a part of the enter string! Format Tokens It is value taking a second to grasp format tokens – the "%Y-%m-%d %H:%M:%S.%f" from earlier than. Every token represents a special a part of the date-time, like day, month, yr, day of month or week, and many others. The listing of supported tokens is intensive sufficient to allow numerous formatting. Among the generally used ones, that we have additionally used earlier are: %Y: Yr (4 digits) %m: Month %d: Day of month %H: Hour (24 hour) %M: Minutes %S: Seconds %f: Microseconds Notice: All of those tokens, besides the yr, are anticipated to be zero-padded (i.e. August is the eighth month, and is zero-padded to 08). Utilizing strptime() Format Tokens to Convert String to Totally different Datetime Format If the format of a string is understood, it may be simply parsed to a datetime object utilizing strptime(). Let’s check out a non-trivial instance that interprets from one format to a different: import datetime date_time_str = 'Jul 17 2022 9:20AM' date_time_obj = datetime.datetime.strptime(date_time_str, '%b %d %Y %I:%Mpercentp') print('Date:', date_time_obj.date()) print('Time:', date_time_obj.time()) print('Date-time:', date_time_obj) The enter string was of 1 format – “Jul 17 2022 9:20AM”. Figuring out this format, we mapped the constituent parts to the ISO 8601 format and transformed it to a datetime object: Date: 2022-07-17 Time: 09:20:00 Date-time: 2022-07-17 09:20:00 Here is a brief listing of widespread string-formatted datetimes and their corresponding codecs for strptime(): "Jun 28 2018 at 7:40AM" -> "%b %d %Y at %I:%Mpercentp" "September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S" "Solar,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%Mpercentp" "Mon, 21 March, 2015" -> "%a, %d %B, %Y" "2018-03-12T10:12:45Z" -> "%Y-%m-%dTpercentH:%M:%SZ" You’ll be able to parse a date-time string of any format – so long as you utilize the proper string of format tokens for the enter you are receiving. Convert String to Datetime with Timezones Dealing with date-times turns into extra advanced whereas coping with timezones. All above examples thus far are naive to the timezone. These are often called naive datetime objects. Nonetheless, the datetime objects comprise a discipline precisely for storing timezone-related knowledge – tzinfo: import datetime as dt dtime = dt.datetime.now() print(dtime) print(dtime.tzinfo) The tzinfo discipline is supposed to be a datetime.timezone object, denoting the timezone info. It is None by default, and denotes that the datetime object is timezone-naive. A quite common exterior library for dealing with timezones is pytz. You’ll be able to set PyTz objects because the tzinfo discipline too. If you do not have it already – set up it through: $ pip set up pytz Utilizing PyTz, we are able to create an anchor for time-zone conscious datetimes, akin to UTC: import datetime as dt import pytz dtime = dt.datetime.now(pytz.utc) print(dtime) print(dtime.tzinfo) Output: 2022-12-01 02:07:41.960920+00:00 UTC It is now not 11AM, however 2AM, as a result of we have set the timezone a couple of hours again! This adjustments the timezone of the datetime. +00:00 is the distinction between the displayed time and the UTC time as the worldwide coordination anchor. We have set the time to be in UTC, so the offset is 00:00. It is a timezone-aware object. Equally, we are able to swap the identical datetime’s interpretation between timezones. Let’s convert a string, akin to “2022-06-29 17:08:00” to a datetime after which localize it to the “America/New_York” timezone: import datetime as dt import pytz date_time_str = '2022-06-29 17:08:00' date_time_obj = dt.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') timezone = pytz.timezone('America/New_York') timezone_date_time_obj = timezone.localize(date_time_obj) print(timezone_date_time_obj) print(timezone_date_time_obj.tzinfo) Notice: Localization turns a timezone-naive datetime right into a timezone-aware datetime, and treats the timezone because the native one. Thus, the datetime stays the identical, however given the totally different timezone, it now not represents the identical cut-off date unbound from timezones. We get the identical datetime worth, offset by -04:00 in comparison with the UTC time: 2022-06-29 17:08:00-04:00 America/New_York 17:08 in Tokyo is not the identical cut-off date as 17:08 in New York. 17:08 in Tokyo is 3:08 in New York. The right way to discover all the timezone codes/aliases? To search out all the out there timezones, examine the all_timezones discipline, which is a listing of all the out there timezones: print(f'There are {len(pytz.all_timezones)} timezones in PyTzn') for time_zone in pytz.all_timezones: print(time_zone) Take a look at our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and really be taught it! There are 594 timezones in PyTz Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera ... Change Datetime’s Timezone We will convert timezone of a timezone-aware datetime object from one area to a different, as a substitute of localizing a timezone-naive datetime via the lens of some timemzone. That is totally different from localization, as localization represents a special cut-off date, however changing the timezone of an object represents the identical cut-off date, via a special lens: import datetime as dt import pytz timezone_nw = pytz.timezone('America/New_York') nw_datetime_obj = dt.datetime.now(timezone_nw) timezone_london = pytz.timezone('Europe/London') london_datetime_obj = nw_datetime_obj.astimezone(timezone_london) print('America/New_York:', nw_datetime_obj) print('Europe/London:', london_datetime_obj) First, we created one datetime object with the present time and set it because the “America/New_York” timezone. Then utilizing the astimezone() technique, we’ve got transformed this datetime to “Europe/London” timezone. Each datetimes will print totally different values, utilizing UTC offset as a reference hyperlink between them: America/New_York: 2022-11-30 21:24:30.123400-05:00 Europe/London: 2022-12-01 02:24:30.123400+00:00 2:24 the following day in London is the identical cut-off date as 21:24 yesterday in New York as London is 5h forward. As anticipated, the date-times are totally different since they’re about 5 hours aside. Convert String to Datetime Utilizing Third Get together Libraries Python’s datetime module can convert all several types of strings to a datetime object. However the principle drawback is that with a purpose to do that you should create the suitable formatting code string that strptime() can perceive. Creating this string takes time and it makes the code more durable to learn. As an alternative, we are able to use different third-party libraries to make it simpler. In some instances these third-party libraries even have higher built-in help for manipulating and evaluating date-times, and a few even have timezones built-in, so that you need not embody an additional PyTz package deal. Let’s check out few of those libraries within the following sections. Convert String to Datetime with dateutil The dateutil module is an extension to the datetime module. One benefit is that we need not cross any parsing code to parse a string! To routinely convert a string to datetime with out a format token utilizing Python’s dateutil: from dateutil.parser import parse datetime = parse('2018-06-29 22:21:41') print(datetime) This parse operate will parse the string routinely! You do not have to incorporate any format string. Let’s attempt to parse several types of strings utilizing dateutil: from dateutil.parser import parse date_array = [ '2018-06-29 08:15:27.243860', 'Jun 28 2018 7:40AM', 'Jun 28 2018 at 7:40AM', 'September 18, 2017, 22:19:55', 'Sun, 05/12/1999, 12:30PM', 'Mon, 21 March, 2015', '2018-03-12T10:12:45Z', '2018-06-29 17:08:00.586525+00:00', '2018-06-29 17:08:00.586525+05:00', 'Tuesday , 6th September, 2017 at 4:30pm' ] for date in date_array: print('Parsing: ' + date) dt = parse(date) print(dt.date()) print(dt.time()) print(dt.tzinfo) print('n') Output: Parsing: 2018-06-29 08:15:27.243860 2018-06-29 08:15:27.243860 None Parsing: Jun 28 2018 7:40AM 2018-06-28 07:40:00 None Parsing: Jun 28 2018 at 7:40AM 2018-06-28 07:40:00 None Parsing: September 18, 2017, 22:19:55 2017-09-18 22:19:55 None Parsing: Solar, 05/12/1999, 12:30PM 1999-05-12 12:30:00 None Parsing: Mon, 21 March, 2015 2015-03-21 00:00:00 None Parsing: 2018-03-12T10:12:45Z 2018-03-12 10:12:45 tzutc() Parsing: 2018-06-29 17:08:00.586525+00:00 2018-06-29 17:08:00.586525 tzutc() Parsing: 2018-06-29 17:08:00.586525+05:00 2018-06-29 17:08:00.586525 tzoffset(None, 18000) Parsing: Tuesday , sixth September, 2017 at 4:30pm 2017-09-06 16:30:00 None You’ll be able to see that just about any sort of string may be parsed simply utilizing the dateutil module. Whereas that is handy, recall from earlier that having to foretell the format makes the code a lot slower, so in case you’re code requires excessive efficiency then this may not be the fitting strategy to your software. Convert String to Datetime with Maya Maya additionally makes it very straightforward to parse a string and alter timezones. To simply convert a string with Python’s Maya: import maya dt = maya.parse('2018-04-29T17:45:25Z').datetime() print(dt.date()) print(dt.time()) print(dt.tzinfo) Output: 2018-04-29 17:45:25 UTC For changing the time to a special timezone: import maya dt = maya.parse('2018-04-29T17:45:25Z').datetime(to_timezone='America/New_York', naive=False) print(dt.date()) print(dt.time()) print(dt.tzinfo) Output: 2018-04-29 13:45:25 America/New_York Now is not that straightforward to make use of? Let’s check out maya with the identical set of strings we’ve got used with dateutil: import maya date_array = [ '2018-06-29 08:15:27.243860', 'Jun 28 2018 7:40AM', 'Jun 28 2018 at 7:40AM', 'September 18, 2017, 22:19:55', 'Sun, 05/12/1999, 12:30PM', 'Mon, 21 March, 2015', '2018-03-12T10:12:45Z', '2018-06-29 17:08:00.586525+00:00', '2018-06-29 17:08:00.586525+05:00', 'Tuesday , 6th September, 2017 at 4:30pm' ] for date in date_array: print('Parsing: ' + date) dt = maya.parse(date).datetime() print(dt) Output: Parsing: 2018-06-29 08:15:27.243860 2018-06-29 08:15:27.243860+00:00 Parsing: Jun 28 2018 7:40AM 2018-06-28 07:40:00+00:00 Parsing: Jun 28 2018 at 7:40AM 2018-06-28 07:40:00+00:00 Parsing: September 18, 2017, 22:19:55 2017-09-18 22:19:55+00:00 Parsing: Solar, 05/12/1999, 12:30PM 1999-05-12 12:30:00+00:00 Parsing: Mon, 21 March, 2015 2015-03-21 00:00:00+00:00 Parsing: 2018-03-12T10:12:45Z 2018-03-12 10:12:45+00:00 Parsing: 2018-06-29 17:08:00.586525+00:00 2018-06-29 17:08:00.586525+00:00 Parsing: 2018-06-29 17:08:00.586525+05:00 2018-06-29 12:08:00.586525+00:00 Parsing: Tuesday , sixth September, 2017 at 4:30pm 2017-09-06 16:30:00+00:00 As you may see, all the date codecs have been efficiently parsed! If we do not present the timezone data then, it routinely converts it to UTC. So, it is very important word that we should present the to_timezone and naive parameters if the time just isn’t in UTC. Convert String to Datetime with Arrow Arrow is one other library for coping with datetime in Python. And like earlier than with maya, it additionally figures out the datetime format routinely. As soon as interpreted, it returns a Python datetime object from the arrow object. To simply convert a string to datetime utilizing Python’s arrow: import arrow dt = arrow.get('2018-04-29T17:45:25Z') print(dt.date()) print(dt.time()) print(dt.tzinfo) Output: 2018-04-29 17:45:25 tzutc() And right here is how you should use arrow to transform timezones utilizing the to() technique: import arrow dt = arrow.get('2018-04-29T17:45:25Z').to('America/New_York') print(dt) print(dt.date()) print(dt.time()) Output: 2018-04-29T13:45:25-04:00 2018-04-29 13:45:25 As you may see the date-time string is transformed to the “America/New_York” area. Now, let’s once more use the identical set of strings we’ve got used above: import arrow date_array = [ '2018-06-29 08:15:27.243860', '2018-03-12T10:12:45Z', '2018-06-29 17:08:00.586525+00:00', '2018-06-29 17:08:00.586525+05:00', ] for date in date_array: dt = arrow.get(date) print('Parsing: ' + date) print(dt) This code will fail for the date-time strings which were commented out, which is over half of our examples. The output for different strings will likely be: Parsing: 2018-06-29 08:15:27.243860 2018-06-29T08:15:27.243860+00:00 Parsing: 2018-03-12T10:12:45Z 2018-03-12T10:12:45+00:00 Parsing: 2018-06-29 17:08:00.586525+00:00 2018-06-29T17:08:00.586525+00:00 Parsing: 2018-06-29 17:08:00.586525+05:00 2018-06-29T17:08:00.586525+05:00 With the intention to appropriately parse the date-time strings which are commented out, you will must cross the corresponding format tokens to present the library clues as to tips on how to parse it. Conclusion On this article we’ve got proven other ways to parse a string to a datetime object in Python. You’ll be able to both go for the default Python datetime library or any of the third-party libraries talked about on this article, amongst many others. The primary drawback with the default datetime package deal is that we have to specify the parsing code manually for nearly all date-time string codecs. So, in case your string format adjustments sooner or later, you’ll possible have to alter your code as effectively. However many third-party libraries, like those talked about right here, deal with it routinely. Another drawback we face is coping with timezones. One of the best ways to deal with them is all the time to retailer the time in your database as UTC format after which convert it to the person’s native timezone when wanted. These libraries aren’t solely good for parsing strings, however they can be utilized for lots of several types of date-time associated operations. I would encourage you to undergo the paperwork to be taught the functionalities intimately. Share FacebookTwitterPinterestWhatsApp Previous articleImplementing tags utilizing SwiftUI – LogRocket WeblogNext article3d – How do I transfer an object alongside its native axis? Adminhttps://www.handla.it RELATED ARTICLES Programming Testing Node.js Code with Mocha and Chai December 1, 2022 Programming Steady supply, meet steady safety November 30, 2022 Programming Convert YAML Array into Java Record with SnakeYAML November 30, 2022 LEAVE A REPLY Cancel reply Comment: Please enter your comment! Name:* Please enter your name here Email:* You have entered an incorrect email address! Please enter your email address here Website: Save my name, email, and website in this browser for the next time I comment. - Advertisment - Most Popular 3d – How do I transfer an object alongside its native axis? December 1, 2022 Implementing tags utilizing SwiftUI – LogRocket Weblog December 1, 2022 SPHERE Receives $31M for Collection B Funding From Edison Companions, Forgepoint Capital December 1, 2022 Anker Soundcore Liberty 4 evaluate December 1, 2022 Load more Recent Comments