Change date format in python

In this tutorial we will learn about  change date format in python.

Table of contents:

  • Introduction
  • Change date format in python
  • Reference
  • Conclusion

Introduction:

The ‘datetime’ module in python is a powerful tool for handiling date and time. It provides classes for manipulating dates. It enters a python expression enrichment to convert dates from one format to another . In this  we use some expressions :

  • Convert a date from YYYY-MM-DD to MM-DD-YY
  • parse the original date string into  ‘datetime’object.
  • Format the ‘date’ object  into the desired string format.

    parding the date string:

  • ‘datetime.striptime(date_str, “%Y-%m-%d)’: now this function Parses the date string(‘date_str’) using the formate’”%Y – %m – %d”‘.the format codes are:
  • `%Y`:Four-digit year
  • `%m`: Two-digit year
  • `%d`: Two-digit day

    formatting the `datetime` Object:

  • date_obj.strftime("%d-%m-%Y"):this function converts the `datetime` object(`date_obj`) back into sting using the new format `"%d-%m-%Y"`. the format codes are:
  • `%d`: Two-digit day
  • `%m` : Two-digit month

`%Y` : Four-digit year

example:

import datetime

date_input = '20190707'
datetime_object = datetime.datetime.strptime(date_input, '%Y%m%d')

new_format = datetime_object.strftime('%m-%d-%Y')
new_format_1 = datetime_object.strftime('%m/%d/%Y')

print(new_format)  
print(new_format_1)

Output:

07-07-2019
07/07/2019

References : ‎
https://docs.python.org/3/library/datetime.html

https://docs.python.org/3/library/datetime.html

conclusion :

Changing date formats in Python is essential for data cleaning and ensuring consistency across different systems. The datetime module offers a robust and flexible approach to handle these conversions effectively. By understanding and utilizing strptime for parsing and strftime for formatting, you can easily convert date strings between various formats as required for your applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top