I am logging some stuff in a JSON file, I have a datetime object that I convert into a string so that I can log it in the JSON (it doesn't accept the datetime object).
import datetime
now = datetime.datetime()
jsonFile.dumps(now)
# Dumping datetime object as string into JSON holding my logs, I should note I'm not actually dumping the logs, I'm getting them from a different source and logging them but this is probably what the source did
print(jsonFile["time"].now)
# When I try to use .now for the datetime object, it recognizes it as a string rather than a datetime object
My question is how do I convert the datetime string back into a datetime object. I know about strptime, I just don't know what format would make it compatible with other datetime.now objects.
Any time I try to use strptime, I use the '(%Y, %m, %d, %H, %M, %S)' format and get this error:
ValueError: time data '2021-12-10 23:34:56.234000' does not match format '(%Y, %m, %d, %H, %M, %S)'
So what is the correct format for a default datetime object?
It would help if you have provided the format of the datetime format you saving in the json file. However let assume your date is as "YYYY-MM-DD HH:MM:SS" format. The procedure is as follows,
from datetime import datetime
dt_string = "2021-12-11 09:15:32"
# Considering date is in yyyy/mm/dd format
dt_object1 = datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
make sure you're using strptime with correct syntax.
Related
I'm trying to convert a string to datetime with dd/mm/YYYY format, but the function "strptime" seems isn't working properly. The result format isn't in the same that i am specifying in the function.
import datetime
from datetime import datetime
from datetime import date
today = date.today()
print (today)
today = today.strftime("%d-%m-%Y %H:%M:%S")
print (today)
today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)
My output is this:
2022-08-26
26-08-2022 00:00:00
2022-08-26 00:00:00
it seems that after the strftime function, the format is right, but when i call the strptime function, its getting back to the previous format "YY-mm-dd"
today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)
That part is creating a datetime object.
You can do:
print (today.strftime("%d-%m-%Y %H:%M:%S"))
again in the final line
it seems that after the strftime function, the format is right, but when i call the strptime function, its getting back to the previous format "YY-mm-dd"
That is because print(today) determines the format since you didn't specify one. As other's pointed out, today is a datetime object. When you print() a datetime object, python will choose a format for you, I assume based on your system's locale settings.
One concept to understand here is the difference between a value and the representation of that value as a string. This is what formatting a datetime is for.
I suggest you don't worry about the output here too much. As long as your explicit format with strftime() gives you the correct representation, then you are good. This formatting should only be used for output. Otherwise, store datetimes and datetime objects in your variables.
I get time data from API response like '2020-02-25T20:53:06.706401+07:00'. Now I want to convert to %Y-%m-%d %H:%M:%s format. But I do not know exactly standard format of that time data.
Help me find the time format!
In your case you can use datetime.fromisoformat:
from datetime import datetime
datetime_object = datetime.fromisoformat("2020-02-25T20:53:06.706401+07:00")
print(datetime_object.strftime("%Y-%m-%d %H:%M:%s"))
Prints
2020-02-25 20:53:1582656786
Other options:
Use the third party dateutil library
Use datetime.strptime which parses the string according to format
You can convert to a datetime object and then optionally recreate the string in a new format as follows:
from datetime import datetime
d = "2020-02-25T20:53:06.706401+07:00"
dt = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z")
# Note the capital S
new = dt.strftime("%Y-%m-%d %H:%M:%S")
However the new value here has lost the timezone offset information. I assume that's OK for you. I also used %S instead of %s since I assume that's really what you want. The lowercase %s wouldn't really make sense, and is also not truly supported by Python.
I am currently having an issue converting an incoming datetime string to a datetime object using Python's built in strptime() method. Here is what I currently have:
def fixDateTimeField(datetimeString):
# Convert from 2012-08-07T00:00:00Z to 2012-08-07T00:00:00.000Z
datetime_object = datetime.strptime(datetimeString, "%y-%m-%dT%H:%M:%SZ")
return datetime_object
Like the comment says, I am trying to convert the string "2012-08-07T00:00:00Z" to a datetime object that looks like 2012-08-07T00:00:00.000Z but I am getting an error in my console that says: "ValueError: time data '2012-08-07T00:00:00Z' does not match format '%y-%m-%dT%H:%M:%SZ'". The format seems correct to me and i'm not seeing the issue.
Thanks in advance!
%y is for two-digit years. You have a four-digit year.
Try using %Y instead.
>>> from datetime import datetime
>>> datetimeString = "2012-08-07T00:00:00Z"
>>> print(datetime.strptime(datetimeString, "%Y-%m-%dT%H:%M:%SZ"))
2012-08-07 00:00:00
A nice way to parse your iso-8601 datetime string "2012-08-07T00:00:00Z" to a datetime object is using dateutil.
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
With strptime:
datetime.datetime.strptime( "2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")
Works. As an other answer said, the Y must be capitalized for strptime to work with 4 digit years.
I am relatively new to python.
I have a timestamp of the format - 2016-12-04T21:16:31.265Z. It is of a type string. I want to know how can I parse the above timestamp in python.
I was looking through the datetime library, but seems like it accepts only floats. How do I get the time stamp parsed? I was trying to hunt for something like an equivalent of Instant (in java) for python?
import datetime
time_str = '2016-12-04T21:16:31.265Z'
time_stamp = datetime.datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(time_stamp)
Reference: https://docs.python.org/2/library/datetime.html; (8.1.7. strftime() and strptime() Behavior)
To parse it according to your current timezone, using the format used by the Unix date command:
import re
from calendar import timegm
from datetime import datetime
from time import localtime, strptime, strftime
fmt = "%a %b %d %H:%M:%S %Z %Y"
ts = "2016-12-04T21:16:31.265Z"
strftime(fmt, localtime(timegm(strptime(re.sub("\.\d+Z$", "GMT", ts), '%Y-%m-%dT%H:%M:%S%Z'))))
I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:00:03
regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7
The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.
parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with
print dt.strftime("%d-%m-%Y %H:%M:%S")
it will work as you expect.
The standard lib (built-in) datetime lib can do this easily.
from datetime import datetime
my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")