Saturday, 20 March 2021

Python strptime() vs Python strftime()

The strftime() method returns a string representing date and time using date , time or datetime object. So it is used to convert the date-time object into string format.

Let’s take a look at an example:

    from datetime import datetime
    t = datetime.now()
    print('current-time--->', t)
 #output
    current-time---> 2023-01-10 23:16:42.511274

now let's play around strftime
 
    print(t.strftime('%y-%m-%d'))
output:-->  
    23-01-10
    print(t.strftime('%Y-%m-%d'))
output:--> 
    2023-01-10
    print(t.strftime('%y-%m-%d %H:%M'))
output:--> 
    23-01-10 23:16

So basically we can extract any kind of data from date-time object in string format.

The strptime() method creates a datetime object from the given string. It used to convert a given string into python datetime object.

In the same way, let’s look at an example for strptime.

    from datetime import datetime
    t_date = '2023-01-10'
    t_date_obj = datetime.strptime(t_date, '%Y-%m-%d')
output:-->
    datetime.datetime(2023, 1, 10, 0, 0)
 lets add a time as well.
    t_date_time = '2023-01-10T10:10'
    t_date_time_obj = datetime.strptime(t_date, '%Y-%m-%dT%H:%M')
output:-->
    datetime.datetime(2023, 1, 10, 10, 10)

Here t_date_obj and t_date_time_obj now became regular python datetime object and you can start treating them as datetime object further in your program.

It’s really helpful in time formatting, ingesting data in different time format, date-to-string conversion etc.

Do check out the official python documentation for the full list of abbreviations.

Directive Meaning Example
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE)
%A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE)
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, …, 6
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

No comments:

Post a Comment