Str date to datetime python

Create Python Datetime from string

In this article, we are going to see how to create a python DateTime object from a given string.

For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user.

datetime.strptime(date_string, format)

Converting string to DateTime using strptime()

Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this.

Python3

The type of the input date string now is:

The date is 2024-01-21 11:04:19

Converting string containing words to datetime using strptime()

The strptime() method allows you to convert timestamps in “words” to date-time objects too. The snippet below shows it can be done:

Python3

Python strptime() ValueError

DateTime format for the given string must be known, failing which can cause unnecessary problems and errors. the snippet below shows what problems can be caused:

Python3

1st interpretation of date from string is: 2020-11-23 10:14:55

2nd interpretation of date from same string is 2023-11-20 10:55:14

The strptime() method will not work if the string argument is not consistent with the format parameter. The following snippets show an error occurring due to the mismatch in the format specifier.

Python3

ValueError(“time data %r does not match format %r” %(data_string, format))

Format Code List

The format specifiers are mostly the same as for strftime() method. These specifiers are:

Directives Meaning Example
%a Abbreviated weekday name. Sun, Mon, …
%A Full weekday name. Sunday, Monday, …
%w Weekday as a decimal number. 0, 1, …, 6
%d Day of the month as a zero-padded decimal. 01, 02, …, 31
%-d Day of the month as a decimal number. 1, 2, …, 30
%b Abbreviated month name. Jan, Feb, …, Dec
%B Full month name. January, February, …
%m Month as a zero-padded decimal number. 01, 02, …, 12
%-m Month as a decimal number. 1, 2, …, 12
%y Year without century as a zero-padded decimal number. 00, 01, …, 99
%-y Year without century as a decimal number. 0, 1, …, 99
%Y Year with century as a decimal number. 2013, 2019 etc.
%H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23
%-H Hour (24-hour clock) as a decimal number. 0, 1, …, 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
%-I Hour (12-hour clock) as a decimal number. 1, 2, … 12
%p Locale’s AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%-M Minute as a decimal number. 0, 1, …, 59
%S Second as a zero-padded decimal number. 00, 01, …, 59
%-S Second as a decimal number. 0, 1, …, 59
%f Microsecond as a decimal number, zero-padded on the left. 000000 – 999999
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name.
%j Day of the year as a zero-padded decimal number. 001, 002, …, 366
%-j Day of the year as a decimal number. 1, 2, …, 366
%U Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, …, 53
%W Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, …, 53
%c Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
%x Locale’s appropriate date representation. 09/30/13
%% A literal ‘%’ character. %
Читайте также:  Что такое break в python

Источник

How To Convert a String to a datetime or time Object in Python

How To Convert a String to a datetime or time Object in Python

The Python datetime and time modules both include a strptime() class method to convert strings to objects.

In this article, you’ll use strptime() to convert strings into datetime and struct_time() objects.

Converting a String to a datetime object using datetime.strptime()

The syntax for the datetime.strptime() method is:

datetime.strptime(date_string, format) 

The datetime.strptime() method returns a datetime object that matches the date_string parsed by the format. Both arguments are required and must be strings.

For details about the format directives used in datetime.strptime() , refer to the strftime() and strptime() Format Codes in the Python documentation.

Convert String to datetime.datetime() Object Example

The following example converts a date and time string into a datetime.datetime() object, and prints the class name and value of the resulting object:

from datetime import datetime datetime_str = '09/19/22 13:55:26' datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S') print(type(datetime_object)) print(datetime_object) # printed in default format 

Convert String to datetime.date() Object Example

The following example converts a date string into a datetime.date() object, and prints the class type and value of the resulting object:

from datetime import datetime date_str = '09-19-2022' date_object = datetime.strptime(date_str, '%m-%d-%Y').date() print(type(date_object)) print(date_object) # printed in default format 

Convert String to datetime.time() Object Example

The following example converts a time string into a datetime.time() object, and prints the class type and value of the resulting object:

from datetime import datetime time_str = '13::55::26' time_object = datetime.strptime(time_str, '%H::%M::%S').time() print(type(time_object)) print(time_object) 

Convert String to datetime.datetime() Object with Locale Example

The following example converts a German locale date string into a datetime.datetime() object, and prints the class type and value of the resulting object:

from datetime import datetime import locale locale.setlocale(locale.LC_ALL, 'de_DE') date_str_de_DE = '16-Dezember-2022 Freitag' # de_DE locale datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A') print(type(datetime_object)) print(datetime_object) 

Note that the resulting object doesn’t include the weekday name from the input string because a datetime.datetime() object includes the weekday only as a decimal number.

Читайте также:  Database exception in python

Converting a String to a struct_time() Object Using time.strptime()

The syntax for the time.strptime() method is:

time.strptime(time_string[, format]) 

The time.strptime() method returns a time.struct_time() object that matches the time_string parsed by the format. The time_string is required and both arguments must be strings. If format is not provided, the default is:

This corresponds to the format returned by the ctime() function.

The format directives are the same for time.strptime() and time.strftime() . Learn more about the format directives for the time module in the Python documentation.

Convert String to struct_time() Object With Format Provided Example

The following example converts a time string into a time.struct_time() object by providing the format argument, and prints the value of the resulting object:

import time time_str = '11::33::54' time_obj = time.strptime(time_str, '%H::%M::%S') print("A time.struct_time object that uses the format provided:") print(time_obj) 
A time.struct_time object that uses the format provided: time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=33, tm_sec=54, tm_wday=0, tm_yday=1, tm_isdst=-1) 

As shown in the output, when you convert a string into a time.struct_time() object, the strptime() method uses placeholder values for any format directives that aren’t defined in the format argument.

Convert String to struct_time() Object Using Default Format Example

If you don’t provide a format argument when you convert a time string into a time.struct_time() object, then the default format is used and an error occurs if the input string does not exactly match the default format of:

The following example converts a time string into a time.struct_time() object with no format argument provided, and prints the value of the resulting object:

import time # default format - "%a %b %d %H:%M:%S %Y" time_str_default = 'Mon Dec 12 14:55:02 2022' time_obj_default = time.strptime(time_str_default) print("A time.struct_time object that uses the default format:") print(time_obj_default) 
A time.struct_time object that uses the default format: time.struct_time(tm_year=2022, tm_mon=12, tm_mday=12, tm_hour=14, tm_min=55, tm_sec=2, tm_wday=0, tm_yday=346, tm_isdst=-1) 

As shown in the output, when you convert a string into a time.struct_time() object, the strptime() method uses placeholder values for any format directives that aren’t defined in the format argument or by the default format if no format is provided.

Читайте также:  Создаем csv файл php

Troubleshooting strptime() Errors

If the input string can’t be parsed by strptime() using the provided format, then a ValueError is raised. You can use the try block to test for parsing errors, along with the except block to print the results. The ValueError messages that you get when you use the strptime() method clearly explain the root causes of the parsing errors. The following example demonstrates some common errors, such as extra data and a format mismatch:

from datetime import datetime import time datetime_str = '09/19/18 13:55:26' try: datetime_object = datetime.strptime(datetime_str, '%m/%d/%y') except ValueError as ve1: print('ValueError 1:', ve1) time_str = '99::55::26' try: time_object = time.strptime(time_str, '%H::%M::%S') except ValueError as ve2: print('ValueError 2:', ve2) 
ValueError 1: unconverted data remains: 13:55:26 ValueError 2: time data '99::55::26' does not match format '%H::%M::%S' 

Conclusion

In this tutorial, you converted date and time strings into datetime and time objects using Python. Continue your learning with more Python tutorials.

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Источник

Оцените статью