What is the fastest way to trim datetime object of this form 2016-12-14 15:57:16.140645 to become like this: 2016-12-14 15:57:16? doing str('2016-12-14 15:57:16.140645').strip(".")[0] is painfully slow for large datasets and besides I need the returned format to be a datetime object
For those that came here for the actual question 'Remove timezone information from datetime object', the answer would be something like:
datetimeObject.replace(tzinfo=None)
from datetime import datetime, timezone
import time
datetimeObject = datetime.fromtimestamp(time.time(), timezone.utc)
print(datetimeObject)
datetimeObject = datetimeObject.replace(tzinfo=None)
print(datetimeObject)
use strftime if you already have a datetime object
dt.strftime('%Y-%m-%d %H:%M:%S')
If you need a datetime object from a string, the fastest way is to use strptime and a slice:
st = '2016-12-14 15:57:16.140645'
dt = datetime.strptime(st[:19], '%Y-%m-%d %H:%M:%S')
Related
In python, I have a datetime object in python with that format.
datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
In other classes, I'm using this object. When i reach this object,i want to extract time from it and compare string time.
Like below;
if "01:15:13" == time_from_datetime_object
How can I do this?
You need to use the strftime method:
from datetime import datetime
date_time_str = '2021-01-15 01:15:13'
datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
print("match")
If you want to compare it as string:
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
Use its time method to return a time object, which you can compare to another time object.
from datetime import time
if datetime_object.time() == time(1, 15, 13):
...
You may have to be careful with microseconds though, so at some point you might want to do datetime_object = datetime_object.replace(microsecond=0), should your datetime objects contain non-zero microseconds.
I have a dataframe that looks like that:
conversation__created_at
0 2020-10-15T03:39:42.766773+00:00
1 2020-10-14T11:24:33.831177+00:00
2 2020-10-14T08:29:44.192258+00:00
3 2020-10-14T01:42:06.674313+00:00
4 2020-10-13T12:57:04.218184+00:00
How to convert it into GMT +7?
I assume you have a pandas series because the data you posted looks like one.
Then you can use tz_convert, i.e.
import pandas as pd
pd.to_datetime('2020-10-15T03:39:42.766773+00:00').tz_convert('Etc/GMT+7')
As pointed out in the comments, since the datetime carries a T in it, it is of string format, thus we need to convert to datetime first and then convert to the correct timezone.
pd.to_datetime(series).dt.tz_convert('Etc/GMT+7')
You can use datetime library only.
from datetime import datetime, timedelta, timezone
d = datetime.fromisoformat("2020-10-15T03:39:42.766773+00:00")
tz = timezone(timedelta(hours=7))
new_time = d.astimezone(tz)
you can use pytz to set timezone for your datetime instance
for example:
from pytz import timezone
from datetime import datetime
date = datetime.now()
print(date)
tz = timezone("Etc/GMT+7")
date = date.replace(tzinfo=tz)
print(date)
out put:
2020-10-26 10:33:25.934699
2020-10-26 10:33:25.934699-07:00
You can apply pytz.timezone on the df
from pytz import timezone
from datetime import datetime
def myDate(x):
tz = timezone("Etc/GMT+7")
dt = x.replace(tzinfo=tz)
return dt
df['conversation__created_at'] = df.apply(lambda row: myDate(row['conversation__created_at'].to_pydatetime()))
I need to assign to a variable the current datetime string in isoformat like the following:
2018-09-27T16:19:16+02:00
What I'm doing is:
import datetime
....
print(datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat())
But this is going to print the string with utc tz:
2018-09-28T07:05:35+00:00
Not clear yet to me what's the clean way I should change tzinfo param to set wanted tz to UTC+02:00 ?
Thanks
utcnow() already gives you the the time at +00:00, if you'd like to recieve the time at a specific timezone, you should provide the timezone as an argument to now([tz]).
https://docs.python.org/3/library/datetime.html
>>> import datetime as dt
>>> dt.datetime.now(tz = dt.timezone(offset = dt.timedelta(hours = 2))).replace(microsecond = 0).isoformat()
'2018-09-28T09:20:19+02:00'
Apple is returning a strange format for the expiration date of a receipt:
2018-06-18 15:03:55 Etc/GMT
from datetime import datetime
dt = datetime.strptime('2018-06-18 15:03:55 Etc/GMT', '%Y-%m-%d %H:%M:%S %Z')
Etc and GMT are both the same.
I have tried to convert it like this into a datetime object, but failed doing so.
ValueError: time data '2018-06-18 15:03:55 Etc/GMT' does not match format '%Y-%m-%d %H:%M:%S %Z'
Why are there two time zones defined in the first place? And how can I make Python understanding it?
Actually, Etc/GMT appears to be a valid, existing time zone, just datetime does not seem to recognize it. You can do the following if you have the possibility to install pytz:
from datetime import datetime
import pytz
dt, tz = '2018-06-18 15:03:55 Etc/GMT'.rsplit(maxsplit=1) # rsplit() for simplicity, obviously re would make this safer
dto = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(tz))
print(dto) # result: 2018-06-18 15:03:55+00:00
I am not sure if this is the correct approach..but if it helps.
import re
from dateutil.parser import parse
s = '2018-06-18 15:03:55 Etc/GMT'
print( parse(re.sub("(?<=:\d{2}\s).*\/", r"", s)) )
Output:
2018-06-18 15:03:55+00:00
I am using regex to remove Etc/ from the src datetime
Using dateutil to convert to datetime object.
Consider a list of posix time stamps
posix_times = [1490750889, 1490751209, 1490751569]
I would like to convert each element in the array to a text string containing the local date and time in the US/Pacific time zone:
["3/28/2017 18:28:09", "3/28/2017 18:33:29", "3/28/2017 18:39:29"]
What is the simplest way to do this which requires a minimum of package imports?
A related problem was addressed in Converting unix timestamp string to readable date in Python, which offers, for example a solution of the form:
posix_time = 1490750889
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
which does not offer the explicit ability to convert this time to another time zone. Also, it appears that such a method does not work on lists and would require a for loop/list comprehension.
You can do this with the standard datetime library:
In [1]: import datetime
In [2]: posix_times = [1490750889, 1490751209, 1490751569]
In [3]: [datetime.datetime.fromtimestamp(x).strftime("%x %X") for x in posix_times]
Out[3]: ['03/28/17 20:28:09', '03/28/17 20:33:29', '03/28/17 20:39:29']
You can convert a UNIX timestamp into a datetime object and then format it using its strftime method. However, this will give you a timezone-unaware datetime. In order to make it timezone-aware, you'll need to get the timezone from pytz and use the localize method:
from datetime import datetime
from pytz import timezone
# ...
def format_time(time, tz):
localized = tz.localize(datetime.fromtimestamp(time))
return localized.strftime('%d/%m/%Y %H:%M:%S')
us_pacific = timezone('US/Pacific')
dates = map(lambda t: format_time(t, us_pacific), posix_times)