-1

I got stuck trying to change this format of a date, '2022-12-10T11:04:11.373Z' into just the year/month/day. While I read other posts it didn't help, and also how would I take a y/m/d input and compare the formatted date with the date inputted? Thanks for reading and please help me!

I've tried using datetime, strip and some other stuff but none of it worked.

Printer
  • 3
  • 1
  • _Show_ the thing that "didn't work", and show _how_ it didn't work. Without a specific demonstration of what you tried and how it failed, you aren't giving us a "specific technical problem you actually face" as our rules require (see the [mre] page in the Help Center), and are requiring us to guess (perhaps wrongly!) at where you got stuck. – Charles Duffy Jun 18 '23 at 14:46

1 Answers1

0

If I follow your question correctly, I think you're looking for the the 'datetime module' (which you've mentioned) but you also need to know the format string of the given date and how to use format strings generally. Once you know the format of the data you're dealing with, you can parse any date string and provided it's in the correct format, you can then turn it into a datetime object and do comparisons and other operations regardless of the original format of each date. Google the formats to pass to the datetime 'strftime' / 'strptime' methods to get the meanings of the '%' format specifiers; there are quite a few of them. Here's a very simple example using the two formats you've supplied:

#!/usr/bin/python

import datetime
import sys
import argparse

# Correctly fomatted command line args.
string_date1=sys.argv[1]
string_date2=sys.argv[2]

# Put the strings into datetime objects.
datetime_date1=datetime.datetime.strptime(string_date1,"%Y-%m-%dT%H:%M:%S.%fZ")
datetime_date2=datetime.datetime.strptime(string_date2,"%Y/%m/%d")

# Here are the dates packaged up into datetime objects.
print("Date 1: ",datetime_date1)
print("Date 2: ",datetime_date2)

# Compare
print ("Date 1 > date 2: ", datetime_date1 > datetime_date2);
print ("Date 2 > date 1: ", datetime_date2 > datetime_date1);
print ("Dates are equal? ", datetime_date1 == datetime_date2);
print ("Dates are not equal? ", datetime_date1 != datetime_date2);

Usage and output:

$ ./rudimentary_date_compare.py "2021-02-01T20:42:11.393Z" "2022/01/04"

Date 1:  2021-02-01 20:42:11.393000

Date 2:  2022-01-04 00:00:00

Date 1 > date 2:  False

Date 2 > date 1:  True

Dates are equal?  False

Dates are not equal?  True
Community
  • 1
  • 1
Dan
  • 45
  • 4
  • Thanks I thought I needed the y/m/d for it to compare since I've only used lua before, although I think I'm going to come back to it another day cause I need to clear my head haha. – Printer Jun 18 '23 at 15:37