Convert string to datetime in local timezone Python - python-3.x

I have datetime in string needing to be converted in datetime format. Below is my code but it returns error. what I am missing here.
from datetime import datetime
LocalStartTime='2020-09-17T10:55:06.4000000+1000'
datetime_object = datetime.strptime(LocalStartTime, '%Y-%m-%dT%H:%M:%S.%f%z')
Required output shd be date converted in current timezone to format like: '2020-09-17 20:55:06' whatever will be the actual value.
returns below error:
ValueError: time data '2020-09-17T10:55:06.4000000+1000' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

from datetime documentation:
When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).
you have one too many zeros in the float part after the seconds part.
the limitation is 6 digits.
from datetime import datetime
LocalStartTime='2020-09-17T10:55:06.400000+1000'
datetime_object = datetime.strptime(LocalStartTime, '%Y-%m-%dT%H:%M:%S.%f%z')
should work
Edit:
after the OP edited and asked about converting to a different timestamp:
seems like what you're looking for is timestamp() and fromtimestamp()
you can get the timestamp which is a posix timestamp represented as float, and convert it back to datetime object with fromtimestamp() if you want to remove the float part after the seconds you can convert the time stamp to int.
datetime.fromtimestamp(int(datetime_object.timestamp()))

Related

Why does this python datetime format not convert the string of the same format into a datetime object successfully?

import datetime as dt
time_str = '2022-02-25 18:37:46.594385+00:00'
Then I try to convert this into a datetime object as follows:
dt.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S.%f%z')
However it results in the following error:
ValueError: time data '2022-02-25 18:37:46.594385+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f%z'
The error appears to be coming from the %z section of the format, but overall I do not understand why this is not working, since it seems the specified format does match the string format. If you could help identify any issues and suggest a solution to convert the example time_str into a datetime object successfully. Thanks!

Convert number to datetime format

How do I Convert "1561994754" number to "2019-07-01T15:25:54.000000"
I have used :
import datetime
datetime.datetime.fromtimestamp(x['date'] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f')
But I am getting 1970-01-18 19:53:14.754000, can you please guide me to correct function?
Thanks,
Aditya
Removing the / 1000 gives me '2019-07-01 08:25:54.000000', It seems like there was a unit mismatch in your expression. To exactly match the format you're asking for, datetime.datetime.fromtimestamp(x['date'], tz=datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') produces '2019-07-01T15:25:54.000000 (leaving the timezone argument blank defaults to using local time, but the human-readable date in your question uses UTC)
You can try like this!
String myString = String.valueOf(1561994754);
DateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
Date date = format.parse(myString);

Parse string like "15 mins" or "1hr 10mins" to seconds

Does anyone know where I can find a good function that converts a string like "15 mins" or "1hr 20mins" into an integer denoting the number of seconds?
I think you can find your solution here , and you can write your own function which does this, by writing a formal way to parse your time, you can transform your string into a datetime and the rest is straight forward.
from datetime import datetime, timedelta
# we specify the input and the format...
t = datetime.strptime("05:20:25","%H:%M:%S")
# ...and use datetime's hour, min and sec properties to build a timedelta
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
print(delta)
assert(5*60*60+20*60+25 == delta.total_seconds())

python datetime - read a time interval/range from csv formatted as HH:MM-HH:MM

is there a readily-available command in Python's datetime to understand a discrete time range given as HH:MM-HH:MM or HH:MM:ss-HH:MM:ss (e.g. 07:30-12:45)? Such a range would be entered like that in a single cell from a CSV file that the script would access.
Or, might specifying just the start time and then a timedelta value be a better idea?
You can just use split() to separate the two time values, then parse each as a datetime.datetime type and then calculate the timedelta.
Example:
from datetime import datetime
time_string = "07:30-12:45"
separate_times = time_string.split("-")
parsed_times = [datetime.strptime(t, "%H:%M") for t in separate_times]
difference = parsed_times[1] - parsed_times[0]
Calling difference.total_seconds() will return the total seconds between the two times and if you aren't interested in the direction of the difference between the times, you can use abs(difference.total_seconds()).

convertion of datetime to numpy datetime without timezone info

Suppose I have a datetime variable:
dt = datetime.datetime(2001,1,1,0,0)
and I convert it to numpy as follows numpy.datetime64(dt) I get
numpy.datetime64('2000-12-31T19:00:00.000000-0500')
with dtype('<M8[us]')
But this automatically takes into account my time-zone (i.e. EST in this case) and gives me back a date of 2001-12-31 and a time of 19:00 hours.
How can I convert it to datetime64[D] in numpy that ignores the timezone information and simply gives me
numpy.datetime64('2001-01-01')
with dtype('<M8[D]')
The numpy datetime64 doc page gives no information on how to ignore the time-zone or give the default time-zone as UTC
I was just playing around with this the other day. I think there are 2 issues - how the datetime.datetime object is converted to np.datetime64, and how the later is displayed.
The numpy doc talks about creating a datatime64 object from a date string. It appears that when given a datetime.datetime object, it first produces a string.
np.datetime64(dt) == np.datetime64(dt.isoformat())
I found that I could add timezone info to that string
np.datetime64(dt.isoformat()+'Z') # default assumption
np.datetime64(dt.isoformat()+'-0500')
Numpy 1.7.0 reads ISO 8601 strings w/o TZ as local (ISO specifies this)
Datetimes are always stored based on POSIX time with an epoch of 1970-01-01T00:00Z
As for display, the test_datetime.py file offers some clues as to the undocumented behavior.
https://github.com/numpy/numpy/blob/280f6050d2291e50aeb0716a66d1258ab3276553/numpy/core/tests/test_datetime.py
e.g.:
def test_datetime_array_str(self):
a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")
a = np.array(['2011-03-16T13:55Z', '1920-01-01T03:12Z'], dtype='M')
assert_equal(np.array2string(a, separator=', ',
formatter={'datetime': lambda x :
"'%s'" % np.datetime_as_string(x, timezone='UTC')}),
"['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
So you can customize the print behavior of an array with np.array2string, and np.datetime_as_string. np.set_printoptions also takes a formatter parameter.
The pytz module is used to add further timezone handling:
#dec.skipif(not _has_pytz, "The pytz module is not available.")
def test_datetime_as_string_timezone(self):
# timezone='local' vs 'UTC'
a = np.datetime64('2010-03-15T06:30Z', 'm')
assert_equal(np.datetime_as_string(a, timezone='UTC'),
'2010-03-15T06:30Z')
assert_(np.datetime_as_string(a, timezone='local') !=
'2010-03-15T06:30Z')
....
Examples:
In [48]: np.datetime_as_string(np.datetime64(dt),timezone='local')
Out[48]: '2000-12-31T16:00:00.000000-0800'
In [49]: np.datetime64(dt)
Out[49]: numpy.datetime64('2000-12-31T16:00:00.000000-0800')
In [50]: np.datetime_as_string(np.datetime64(dt))
Out[50]: '2001-01-01T00:00:00.000000Z'
In [51]: np.datetime_as_string(np.datetime64(dt),timezone='UTC')
Out[51]: '2001-01-01T00:00:00.000000Z'
In [52]: np.datetime_as_string(np.datetime64(dt),timezone='local')
Out[52]: '2000-12-31T16:00:00.000000-0800'
In [81]: np.datetime_as_string(np.datetime64(dt),timezone=pytz.timezone('US/Eastern'))
Out[81]: '2000-12-31T19:00:00.000000-0500'

Resources