How to get the format of a date in python

I'm getting a date as a string, then I'm parsing it to datetime object. Is there any way to check what's is the date format of the object?

Let's say that this is the object that I'm creating:

modified_date = parser.parse("2015-09-01T12:34:15.601+03:00")

How can i print or get the exact date format of this object, i need this in order to verify that it's in the correct format, so I'll be able to to make a diff of today's date and the given date.

How to get the format of a date in python

wim

312k95 gold badges570 silver badges709 bronze badges

asked Dec 3, 2015 at 18:27

Alex BrodovAlex Brodov

3,26518 gold badges40 silver badges66 bronze badges

7

I had a look in the source code and, unfortunately, python-dateutil doesn't expose the format. In fact it doesn't even generate a guess for the format at all, it just goes ahead and parses - the code is like a big nested spaghetti of conditionals.

You could have a look at dateinfer which looks to be what you're searching for, but these are unrelated libraries so there is no guarantee at all that python-dateutil will parse with the same format that dateinfer suggests.

>>> from dateinfer import infer
>>> s = "2015-09-01T12:34:15.601+03:00"
>>> infer([s])
'%Y-%d-%mT%I:%M:%S.601+%m:%d'

Look at that .601. Close but not cigar. I think it has probably also mixed up the month and the day. You might get better results by giving it more than one date string to base the guess upon.

answered Dec 3, 2015 at 18:58

How to get the format of a date in python

1

i need this in order to verify that it's in the correct format

If you know the expected time format (or a set of valid time formats) then you could just parse the input using it: if it succeeds then the time format is valid (the usual EAFP approach in Python):

for date_format in valid_date_formats:
    try:
        return datetime.strptime(date_string, date_format), date_format
    except ValueError: # wrong date format
        pass # try the next format
raise ValueError("{date_string} is not in the correct format. "
                 "valid formats: {valid_date_formats}".format(**vars()))

Here's a complete code example (in Russian -- ignore the text, look at the code).

If there are many valid date formats then to improve time performance you might want to combine them into a single regular expression or convert the regex to a deterministic or non-deterministic finite-state automaton (DFA or NFA).

In general, if you need to extract dates from a larger text that is too varied to create parsing rules manually; consider machine learning solutions e.g., a NER system such as webstruct (for html input).

answered Dec 4, 2015 at 13:37

jfsjfs

382k181 gold badges946 silver badges1618 bronze badges

4

In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values. 

Required library 

import datetime

The datetime.time method

Time values can be represented using the time class. The attributes for the time class include the hour, minute, second, and microsecond.

Syntax of datetime.time

time(hour, minute, second, microsecond)

Example 1:

Python3

import datetime

tm = datetime.time(2, 25, 50, 13)

print(tm)

Output

02:25:50.000013

Example 2: 

There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanoseconds, range is between 0 to 999999. If the range exceeds, the compiler shows a ValueError. The instance of time class consists of three instance attributes namely hour, minute, second, and microsecond. These are used to get specific information about the time. 

Python3

import datetime

tm = datetime.time(1, 50, 20, 133257)

print('Time tm is ',

      tm.hour, ' hours ',

      tm.minute, ' minutes ',

      tm.second, ' seconds and ',

      tm.microsecond, ' microseconds')

Output

Time tm is 1 hours 50 minutes 20 seconds and 133257 microseconds

The datetime.date method

The values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day. 

Syntax of datetime.date

date(yyyy, mm, dd)

Example 1:

Python3

import datetime

date = datetime.date(2018, 5, 12)

print('Date date is ', date.day,

      ' day of ', date.month,

      ' of the year ', date.year)

Output

Date date is  12  day of  5  of the year  2018

Example 2: 

To get today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used. 

Python3

import datetime

tday = datetime.date.today()

daytoday = tday.ctime()

print("The date today is ", tday)

print("The date info. is ", daytoday)

Output

The date today is  2020-01-30
The date info. is  Thu Jan 30 00:00:00 2020

Convert string to date using DateTime

Conversion from string to date is many times needed while working with imported data sets from a CSV or when we take inputs from website forms. To do this, Python provides a method called strptime()

Syntax: datetime.strptime(string, format)

Parameters:

  • string – The input string.
  • format – This is of string type. i.e. the directives can be embedded in the format string.

Example: 

Python3

from datetime import datetime

print(datetime.strptime('5/5/2019',

                        '%d/%m/%Y'))

Output

2019-05-05 00:00:00

Convert dates to strings using DateTime

Date and time are different from strings and thus many times it is important to convert the DateTime to string. For this, we use strftime() method. 

Syntax of datetime.strftime

Syntax: datetime.strftime(format, t)

Parameters:

  • format – This is of string type. i.e. the directives can be embedded in the format string.
  • t – the time to be formatted.

Example 1:

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%b %d %Y %H:%M:%S"))

Output 

May 12 2018 02:25:50

Example 2:

The same example can also be written in a different place by setting up the print() method. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%H:%M:%S %b %d %Y"))

Output 

02:25:50 May 12 2018 

%H, %M and %S displays the hour, minutes and seconds respectively. %b, %d and %Y displays 3 characters of the month, day and year respectively. Other than the above example the frequently used character code List along with its functionality are:

Frequently used character code in DateTime

  • %a: Displays three characters of the weekday, e.g. Wed. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%a"))

Output

Sat
  • %A: Displays name of the weekday, e.g. Wednesday. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%A"))

Output

Saturday
  • %B: Displays the month, e.g. May. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%B"))

Output

May
  • %w: Displays the weekday as a number, from 0 to 6, with Sunday being 0. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%w"))

Output

6
  • %m: Displays month as a number, from 01 to 12. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%m"))

Output

5
  • %p: Define AM/PM for time. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%p"))

Output

PM
  • %y: Displays year in two-digit format, i.e “20” in place of “2020”. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("% y"))

Output

18
  • %f: Displays microsecond from 000000 to 999999. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("% f"))

Output

000013
  • %j: Displays number of the day in the year, from 001 to 366. 

Python3

import datetime

x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)

print(x.strftime("%f"))

Output

132

How do I print date format in Python?

We have used the following character strings to format the date:.
%b : Returns the first three characters of the month name. ... .
%d : Returns day of the month, from 1 to 31. ... .
%Y : Returns the year in four-digit format. ... .
%H : Returns the hour. ... .
%M : Returns the minute, from 00 to 59. ... .
%S : Returns the second, from 00 to 59..

What is the format of a date in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I format a date in YYYY

In Python, we can easily format dates and datetime objects with the strftime() function. For example, to format a date as YYYY-MM-DD, pass “%Y-%m-%d” to strftime(). If you want to create a string that is separated by slashes (“/”) instead of dashes (“-“), pass “%Y/%m/%d” to strftime().

How do I check if a date is in mm/dd/yyyy in Python?

“how to verify date dd/mm/yyyy python” Code Answer.
>>> import datetime..
>>> def validate(date_text):.
datetime. datetime. strptime(date_text, '%Y-%m-%d').
except ValueError:.
raise ValueError("Incorrect data format, should be YYYY-MM-DD").

How do I get the exact date in Python?

Example 1: Python get today's date Then, we used the date.today() method to get the current local date. By the way, date.today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.

How do I change date format in Python?

from datetime import datetime..
date_time_str = '18/09/19 01:55:19'.
date_time_obj = datetime. strptime(date_time_str, '%d/%m/%y %H:%M:%S').
print ("The type of the date is now", type(date_time_obj)).