Parsing a time instant in python - python

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'))))

Related

How to format string to be a default datetime object

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.

Convert json field to datetime in Python

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.

Python Datetime object

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.

How to convert date string to a datetime object in a specified timezone

I can convert a given date string formatted in YYYY-MM-DD to a datetime object using:
from datetime import datetime
dt = datetime.strptime(date_str, '%Y-%m-%d')
However, this uses the current machine's timezone by default.
Is there a way to specify a specific timezone (such as UTC, PST, etc) in the conversion so that the obtained datetime object is in that timezone.
I am trying to do this in Python 3.4.3.
This is not possible using only Python's standard library.
For full flexibility, install python-dateutil and pytz and run:
date_str = '2015-01-01'
dt = pytz.timezone('Europe/London').localize(dateutil.parser.parse(date_str))
This gives you a datetime with Europe/London timezone.
If you only need parsing of '%Y-%m-%d' strings then you only need pytz:
from datetime import datetime
naive_dt = datetime.strptime(date_str, '%Y-%m-%d')
dt = pytz.timezone('Europe/London').localize(naive_dt)

Local Time To UTC time pytz

I converted python datetime with help of pytz.
Convertion is like this
2013-08-23T09:53:03 to 2013-08-23T15:23:03+05:30 (time is changed
according timezone)
now the problem is "At at another loaction i get time as string 2013-08-23T15:23:03+05:30 how can i convert this string to 2013-08-23T09:53:03
thanks in advance
You can use the very useful dateutil package
from dateutil import parser
import pytz
UTC = pytz.timezone('UTC')
date = parser.parse("2013-08-23T15:23:03+05:30")
dateutc = date.astimezone(UTC)
print dateutc.isoformat()
# or user strptime to have in the format you want (without time zone)
print dateutc.strftime("%Y-%m-%dT%H:%M:%S")

Categories

Resources