Convert object to date 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. %

Источник

Convert datetime Object to Date & Vice Versa in Python (2 Examples)

TikTok Icon Statistics Globe

This page shows how to transform a datetime object to a date and vice versa in the Python programming language.

The table of content is structured as follows:

Example 1: Convert datetime Object into Date

This example explains how to convert a datetime object into a date.

As a first step, we have to import the datetime module into Python:

from datetime import datetime

Next, we can create a datetime object containing the current date as shown below:

my_datetime = datetime.now() print(my_datetime) # 2021-11-22 16:15:07.540406

As you can see, our example date is the 22nd of November 2021 at 4:15:07 pm.

If we now want to extract only the date from this datetime object, we can use the date() function as shown in the following Python code:

my_date = datetime.date(my_datetime) print(my_date) # 2021-11-22

The previous Python code has created a new data object called my_date, which contains only the date of our datetime object (i.e. 2021-11-22).

Example 2: Convert date Object into datetime

This example explains how to combine a date and a time object into a datetime object, i.e. the other way around compared to Example 1.

Consider the following example date…

my_date2 = datetime(2022, 10, 17, 13, 27).date() print(my_date2) # 2022-10-17

…and the following example time:

my_time2 = datetime(2022, 10, 17, 13, 27).time() print(my_time2) # 13:27:00

Now, we can combine these two data object into a datetime object using the combine() function of the datetime module:

my_datetime2 = datetime.combine(my_date2, my_time2) print(my_datetime2) # 2022-10-17 13:27:00

The output of the previous syntax is a properly formatted datetime object in Python.

Video, Further Resources & Summary

Would you like to know more on how to convert datetime objects to dates and vice versa in Python? In this case, you should have a look at the following YouTube video of the YouTube channel of Code Remedies.

The video explains how to convert strings and numbers into the datetime format:

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

If you accept this notice, your choice will be saved and the page will refresh.

accept

Accept YouTube Content

Furthermore, you may have a look at the other Python and datetime tutorials on this website:

This tutorial has shown how to switch from datetime to only date and the other way around in the Python programming language. In case you have any further questions, you may leave a comment below.

This tutorial was created in collaboration with Gottumukkala Sravan Kumar. Please have a look at Gottumukkala’s author page to get more information about his academic background and the other articles he has written for Statistics Globe.

Источник

Читайте также:  Php символ или код
Оцените статью