Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Time Formats in Python

What are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas?

  • 2013-07-12T07:00:00Z

  • 2013-07-10T11:00:00.000Z

Thanks in advance

like image 287
user1579970 Avatar asked Jul 11 '13 13:07

user1579970


People also ask

How do I set date format 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.

Is there a date format in Python?

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

What is Strftime and Strptime in Python?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.


1 Answers

That extra .000 is micro seconds.

This will convert a date string of a format to datetime object.

import datetime d1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ") d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ") 

Then convert them into any format depending on your requirement, by using:

new_format = "%Y-%m-%d" d1.strftime(new_format) 
like image 85
Sudipta Avatar answered Oct 08 '22 00:10

Sudipta