How to convert string with timezone string to datetime? - python

I have a string like this: '2005-01-03 16:00:00:000 America/New_York', the simplest way to convert it to a datetime instance I could come up with is as below:
ts=r'2005-01-03 16:00:00:000 America/New_York'
import re
pos=re.match(r'[\d\- :]*', ts).end()
tzs=ts[pos:]
tss=ts[:pos-5]
from pytz import timezone
tz=timezone(tzs)
from dateutil import parser
dt=parser.parse(tss)
d=tz.localize(dt)
print d
#2005-01-03 16:00:00-05:00
which is too complicated I think....
So is there any simpler way to achieve this? Thx in advance ~

How about:
import datetime
import pytz
ts = '2005-01-03 16:00:00:000 America/New_York'
tPart, tzPart = ts.rsplit(' ', 1)
dt = datetime.datetime.strptime(tPart, "%Y-%m-%d %H:%M:%S:%f")
tz = pytz.timezone(tzPart)
d = tz.localize(dt)

Related

Transform datetimes in python

How can I transform a string datetime like this:
"2018-07-13T00:00:00+00:00"
Into this?
"2018-07-13T00:00:00.000000+00:00"
try this out:
from datetime import datetime
datetime_string = "2018-07-13T00:00:00+00:00"
new_datetime_string = datetime.fromisoformat(datetime_string).isoformat(timespec="microseconds")
and for before python V3.7:
date_time = datetime.strptime(datetime_string, '%Y-%m-%dT%H:%M:%S%z').strftime("%Y-%m-%dT%H:%M:%S.%f%z")

How to convert datetime into GMT +7 in Python?

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

How can i add 7 hours into api_time? [duplicate]

I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
Now, I am trying to add 9 hours to the above time, how can I add hours to current time in Python?
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as #eumiro has pointed out in comments - strftime
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime and strftime behavior to better understand how python processes dates and time field
This works for me working with seconds not hours and also using a function to convert back to UTC time.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
This is an answer which is significant for nowadays (python 3.9 or later).
Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
#You can then apply custom time formatting as well as a timezone.
TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
custom_time_format = "%H:%M"
time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)
While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
time_modification = datetime.fromtimestamp(timestring.timestamp())
datetime
https://docs.python.org/3/library/datetime.html
strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
timedelta
https://docs.python.org/3/library/datetime.html#datetime.timedelta
zoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo

Remove timezone information from datetime object

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

Display given datetime in reverse order in python

I have a date timestamp like "2013-12-20 23:40:33". Now, my requirement is to re-format this date in reverse order like :
<seconds><minutes><hr><day><month><year>
in python. Please suggest
Load the string into a datetime object with strptime and format to string with strftime:
>>> from datetime import datetime
>>> datetime.strptime(s, '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')
'33:40:23 20-12-2013'
>>> import datetime
>>> datetime.datetime.strptime('2013-12-20 23:40:33', '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')
'33:40:23 20-12-2013'
If you don't need to validate the time string:
>>> import re
>>> '<%s>' % '><'.join(re.findall(r'\d+', "2013-12-20 23:40:33")[::-1])
'<33><40><23><20><12><2013>'
It is 6 times faster than the corresponding datetime solution:
>>> from datetime import datetime
>>> datetime.strptime("2013-12-20 23:40:33", '%Y-%m-%d %H:%M:%S').strftime('<%S><%M><%H><%d><%m><%Y>')
'<33><40><23><20><12><2013>'
Or 5 times faster than time solution:
>>> import time
>>> time.strftime('<%S><%M><%H><%d><%m><%Y>', time.strptime("2013-12-20 23:40:33", '%Y-%m-%d %H:%M:%S'))
'<33><40><23><20><12><2013>'
d = "2013-12-20 23:40:33"
date = d[17]+d[18]+":"+d[14]+d[15]+":"+d[11]+d[12]+" "+d[8]+d[9]+"-"+d[5]+d[6]+"-"+d[0]+d[1]+d[2]+d[3]
print(d)
print(date)

Categories