This question already has answers here:
Convert zulu time string to MST datetime object
(2 answers)
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 1 year ago.
I know this question has been asked in different forms, but I'm not finding what I need. I'm looking for a way to convert the following date / time to my local time zone using Python. Note the time zone of "Z" and the "T" between the date and time, this is what's throwing me off.
"startTime": "2021-03-01T21:21:00.652064Z"
the datetime module is your friend. You seem to be dealing with a date-time stamp in ISO format. The datetime module has a class method to generate a datetime object from an ISO formatted string.
from datetime import datetime
dateinput = "2021-03-01T21:21:00.652064Z"
stamp = datetime.fromisoformat(dateinput)
But here you will get an error because the trailing 'Z' is not quite right. If you know that it's always going to be there, just lop off the last character. Otherwise you might have to do some string manipulation first.
stamp = datetime.fromisoformat(dateinput[:-1])
See also the strptime() class method to get datetime objects from arbitrarily formatted strings.
Hoping this helps...
datetime and pytz modules! Also depends on what you need, but below is the date and time object without the miliseconds part and a simple conversion to Berlin timezone.
import datetime
from pytz import timezone
berlin_timezone = pytz.timezone('Europe/Berlin')
your_time = datetime.datetime.strptime(startTime.split(".")[0], "%Y-%m-%dT%H:%M:%S")
your_time_utc = your_time.astimezone(berlin_timezone)
Related
This question already has answers here:
Convert datetime object to a String of date only in Python
(15 answers)
Closed 4 months ago.
I have a JSON that returns a date in the following date format:
datetime(2015, 12, 1)
So the key value from JSON is
'CreateDate': datetime(2015, 1, 1)
In order to be able to subtract two dates, I need to convert above to date format:
YYYY/MM/DD
so in above case that would become: 2015/12/01
Is there a smart way to do that? Is it at all possible? Or do I really have to parse it as a block of text? I tried using datetime.strptime, but I can't get it to work.
datetime(2015,12,1).strftime("%Y/%m/%d")
will do the trick for you. A complete python program would look like this.
# import the datetime and date classes from the datetime module
from datetime import datetime, date
# create your datetime(..) instance from your JSON somehow
# The included Python JSON tools do not usually know about date-times,
# so this may require a special step
# Assume you have a datetime now
dt = datetime(2015,12,1)
# Print it out in your format
print( dt.strftime("%Y/%m/%d") )
Two important details:
You are using just a date in a Python datetime. Nothing wrong with that but just note that the Python datetime module also has a date class
You can enable your JSON encoder/decoder to recognise dates and datetimes automatically but it requires extra work.
Now, to subtract datetimes from each other they should remain as instances of the datetime class. You can not subtract datetimes from each other once they have been formatted as a string.
Once you subtract a Python datetime from an other datetime the result will be an instance of the timedelta class.
from datetime import datetime, timedelta
# time_diff here is a timedelta type
time_diff = datetime(2015,12,1) - datetime(2014,11,1)
Now you can look up the Python timedelta type and extract the days, hours, minutes etc. that you need. Be aware that timedeltas can be a negative if you subtract a later datetime from an earlier one.
The datetime module has a function for doing this which is pretty easy as shown below
from datetime import datetime
print(datetime(2015,12,1).strftime("%Y/%m/%d"))
Also read more about the module here https://docs.python.org/3/library/datetime.html
This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Parsing date, time and zone to UTC datetime object
(1 answer)
Closed 9 months ago.
I have datetime value in format of 2022-01-26T07:01:36-08:00 (based on which user fetches data, it will have local timezone, like -08:00, +05:30)
I want to convert this time into UTC Time.
I saw multiple example of pytz but couldn't figure out how to convert using pytz or datetime. datetime value will be based on machine timezone so I can't hard code timezone value also.
This question already has answers here:
How to convert a UTC datetime to a local datetime using only standard library?
(14 answers)
Closed 2 years ago.
I have time since epoch and I am converting it to datetime.
import datetime
s = '1346114717'
t = datetime.datetime.fromtimestamp(float(s))
is this correct? t is in which timezone? How can I convert it to PST/PDT
Assuming your string represents Unix time / seconds since 1970-1-1, it refers to UTC. You can convert it to datetime like
from datetime import datetime, timezone
s = '1346114717'
dt = datetime.fromtimestamp(int(s), tz=timezone.utc)
print(dt.isoformat())
# 2012-08-28T00:45:17+00:00
Note that if you don't supply a time zone, the resulting datetime object will be naive, i.e. does not "know" of a time zone. Python will treat it as local time by default (your machine's OS setting).
To convert to US/Pacific time, you can use zoneinfo from Python 3.9's standard lib:
from zoneinfo import ZoneInfo
dt_pacific = dt.astimezone(ZoneInfo('US/Pacific'))
print(dt_pacific.isoformat())
# 2012-08-27T17:45:17-07:00
or use dateutil with older versions of Python:
from dateutil.tz import gettz # pip install python-dateutil
dt_pacific = dt.astimezone(gettz('US/Pacific'))
print(dt_pacific.isoformat())
# 2012-08-27T17:45:17-07:00
python datetime is by default time zone unaware(it doesnt have any timezone information). u could make it aware by using pytz. but i would suggest u take a look at a library like arrow which makes things easier.
This question already has answers here:
pytz localize vs datetime replace
(4 answers)
Closed 8 years ago.
Assume that I have a timezone-less datetime object:
import datetime
import pytz
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
dtUnaware = datetime.datetime(1979,2,20,6)
print(dtUnaware.strftime(fmt))
This yields:
1979-02-20 06:00:00
So far, so good. Now, I want to assign a timezone to this object. It seems like I could use either datetime.replace or pytz.localize.
First:
dtAware1 = dtUnaware.replace(tzinfo=pytz.timezone('Asia/Jerusalem'))
print(dtAware1.strftime(fmt))
returns: 1979-02-20 06:00:00 LMT+0221. Secondly:
dtAware2 = pytz.timezone('Asia/Jerusalem').localize(dtUnaware, is_dst=None)
print(dtAware2.strftime(fmt))
returns 1979-02-20 06:00:00 IST+0200.
What's wrong with the first method? It seems to assign a wrong timezone. Am I doing something wrong?
From Pytz documentation : This library differs from the documented Python API for
tzinfo implementations; if you want to create local wallclock
times you need to use the localize() method documented in this
document... Unfortunately these
issues cannot be resolved without modifying the Python datetime
implementation (see PEP-431)
My reading of that is that a pytz timezone is not exactly the same thing as a standard timezone. If you had a genuine timezone, first method should be good, but you have not.
There is a flaw in the datetime API: when you assign a timezone to it, the timezone is not given the opportunity to know the date and time it should be configured for. The historical database that pytz uses goes back a long way, often to periods when the timezone name or offset were different than the ones in use today. Without being given the chance to adjust to a specific date period, the details of the timezone may be wrong.
Using localize is the way around this problem, since both the date and timezone are available within the function at the same time.
I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first.
How do I do this? I can't find any resources that show the date in that format? Thank you.
You need the strptime method. If you're on Python 2.5 or higher, this is a method on datetime, otherwise you have to use a combination of the time and datetime modules to achieve this.
Python 2.5 up:
from datetime import datetime
dt = datetime.strptime(s, "%d/%m/%Y-%H:%M:%S")
below 2.5:
from datetime import datetime
from time import strptime
dt = datetime(*strptime(s, "%d/%m/%Y-%H:%M:%S")[0:6])
You can use the time.strptime() method to parse a date string. This will return a time_struct that you can pass to time.mktime() (when the string represents a local time) or calendar.timegm() (when the string is a UTC time) to get the number of seconds since the epoch.