strptime
How to convert integer into date object python?
This question is already answered, but for the benefit of others looking at this question I’d like to add the following suggestion: Instead of doing the slicing yourself as suggested in the accepted answer, you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion. import … Read more
how to initialize time() object in python
You can create the object without any values: >>> import datetime >>> datetime.time() datetime.time(0, 0) You, however, imported the class datetime from the module, replacing the module itself: >>> from datetime import datetime >>> datetime.time <method ‘time’ of ‘datetime.datetime’ objects> and that has a different signature: >>> datetime.time() Traceback (most recent call last): File “<stdin>”, … Read more
How to remove unconverted data from a Python datetime object
Unless you want to rewrite strptime (a very bad idea), the only real option you have is to slice end_date and chop off the extra characters at the end, assuming that this will give you the correct result you intend. For example, you can catch the ValueError, slice, and try again: def parse_prefix(line, fmt): try: … Read more
Parsing datetime strings containing nanoseconds
You can see from the source that datetime objects don’t support anything more fine than microseconds. As pointed out by Mike Pennington in the comments, this is likely because computer hardware clocks aren’t nearly that precise. Wikipedia says that HPET has frequency “at least 10 MHz,” which means one tick per 100 nanoseconds. If you … Read more
What does the “p” in strptime stand for?
I guess it stands for “parse” because its reverse function is called strftime in Python’s time module wherein the “f” I can reasonably guess stands for “format”.
How to parse timezone with colon
Currently, there is no cure for this, and here is and explanation: https://bugs.python.org/issue15873 more precisely, here: https://bugs.python.org/msg169952 . But you can override this issue, this way: from datetime import datetime d = “2015-04-30T23:59:59+00:00” if “:” == d[-3:-2]: d = d[:-3]+d[-2:] print(datetime.strptime(d, “%Y-%m-%dT%H:%M:%S%z”))
How to format date string via multiple formats in python
Try each format and see if it works: from datetime import datetime def try_parsing_date(text): for fmt in (‘%Y-%m-%d’, ‘%d.%m.%Y’, ‘%d/%m/%Y’): try: return datetime.strptime(text, fmt) except ValueError: pass raise ValueError(‘no valid date format found’)
Display Python datetime without time
print then.date() What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object: then = datetime.datetime.strptime(when, ‘%Y-%m-%d’).date()