I have data in the following format:
{"date":"2020-04-09","minute":"15:59","label":"3:59 PM"}
This datetime is in New York Timezone (not local time). How do I convert it into a unix timestamp?
In general we convert :
import time
import datetime
d = datetime.datetime(y,m,d,h,m,s,ms)
unixtime = time.mktime(d.timetuple())
to change timezone:
d = datetime.datetime(y,m,d,h,m,s,ms,timezoneinfo)
In your case:
import time
import datetime
from dateutil import tz
def convert(y,m,d,h,min,sec,ms):
NYC = tz.gettz('America/ New_York')
d = datetime.datetime(y,m,d,h,min,sec,ms,tzinfo = NYC)
return time.mktime(d.timetuple())
unixtime = time.mktime(d.timetuple())
print(convert(2020,5,3,3,59,0,0))
You can get TZ names from : https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Related
So, I want to convert UTC date time 2021-08-05 10:03:24.585Z to Indian date time how to convert it?
What I tried is
from datetime import datetime
from pytz import timezone
st = "2021-08-05 10:03:24.585Z"
datetime_object = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%fZ')
local_tz = timezone('Asia/Kolkata')
start_date = local_tz.localize(datetime_object)
print(start_date.replace(tzinfo=local_tz))
But Still the output is not with the timezone I have mentioned how can I convert the time and print the time from the time.
Output:
2021-08-05 10:03:24.585000+05:21
You can use sth like this:
from datetime import datetime
from dateutil import tz
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Asia/Kolkata')
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
parse the date/time string to UTC datetime correctly and use astimezone instead of replace to convert to a certain time zone (option for newer Python version (3.9+) in comments):
from datetime import datetime
# from zoneinfo import ZoneInfo
from dateutil.tz import gettz
st = "2021-08-05 10:03:24.585Z"
zone = "Asia/Kolkata"
# dtUTC = datetime.fromisoformat(st.replace('Z', '+00:00'))
dtUTC = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%f%z')
# dtZone = dtUTC.astimezone(ZoneInfo(zone))
dtZone = dtUTC.astimezone(gettz(zone))
print(dtZone.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30
If you just need local time, i.e. your machine's setting, you can use astimezone(None) as well.
In Python 3.10.8
from datetime import datetime
st = "2021-08-05 10:03:24.585Z"
dtUTC = datetime.fromisoformat(st[:-1]+'+00:00')
dtUTC = dtUTC.astimezone()
print(dtUTC.isoformat(timespec='seconds'))
# 2021-08-05T15:33:24+05:30
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()))
In Python, I need to get the actual time of a given string timestamp converted to a different timezone without timezone information. I am using pytz to do this. But all I get is the given DateTime with the timezone information appended to it.
Base datetime : 2020-05-29 19:00:00 (A string datetime without timezone info)
Requirement: When this time is converted to (US Zipcode 90071) -0700 timezone,
it should return "2020-05-29 12:00:00", not "2020-05-29 19:00:00-0700"
Code:
import pytz
from datetime import datetime
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder
date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zip = "90071"
search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zip)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])
tz = pytz.timezone(timezone)
new_timestamp = tz.localize(date_time_obj)
new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')
But this returns 2020-05-29 19:00:00.000000-0700. I need to retrieve a DateTime object/string with the actual time shown in that timezone without a timezone chunk attached to the end of the DateTime.
Assuming your "Base datetime" refers to UTC, you have to add a tzinfo=UTC first before you convert to another timezone. Also, avoid overwriting built-ins like zip. Example using dateutil:
from datetime import datetime
import dateutil
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder
date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zipcode = "90071"
search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zipcode)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])
# localize to UTC first
date_time_obj = date_time_obj.replace(tzinfo=dateutil.tz.UTC)
# now localize to timezone of the zipcode:
new_timestamp = date_time_obj.astimezone(dateutil.tz.gettz(timezone))
new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')
# '05/29/2020 12:00:00'
If you need to use pytz, make sure to use localize instead of replace (even though UTC is an exception).
Sidenote: If your "Base datetime" refers to local time (operating system), you could obtain that timezone by
import time
import dateutil
localtzname = time.tzname[time.daylight]
tz = dateutil.tz.gettz(localtzname)
It appears that your original date and time are in UTC. So for localize to work properly, you have to start with the proper timezone attached.
date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)
Then you can remove it again after the conversion:
return date_time_obj.astimezone(tz).replace(tzinfo=None)
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
import requests
import bs4
root_url = 'url here'
response = requests.get(root_url)
soup = bs4.BeautifulSoup(response.content)
hora = soup.select('span.match-time')[0].get_text()
return - 20:45
I need to convert the string variable "hora" to datetime zone UTC
Update:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/Montevideo')
utc = dt_obj.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
print(central)
return 1900-01-01 15:45:00-03:45
time difference is 3 hours not 3:45.
What is the matter?
Thankyou
See Python'sdatetime library (datetime)
You're going to particularly need to use datetime.strptime to parse 20:45. You'll also need pytz (pip install pytz) to get UTC timezone.
import pytz
import datetime
udt = datetime.datetime.strptime(hora, '%H:%M').time().replace(tzinfo=pytz.UTC)
This is assuming the time you're reading is already in UTC.
datetime.time(*map(int,hora_string.split(":")))
but you would need to know the timezone it is in in order to change it ...
you could also use the dateutil library
import dateutil.parser as p
print p.parse("16:45")
but this will attach todays date to the time , which may not be desireable
from datetime import datetime as dt
hora = "20:45"
the_time = dt.strptime(hora, "%H:%M").time()
This will return a datetime.time() object.
To convert UTC time to a given timezone, you need to know both date and time (utc offset may be different at a different date/time):
>>> from datetime import datetime
>>> import pytz
>>> input_time = datetime.strptime('20:45', '%H:%M').time()
>>> utc_dt = datetime.combine(datetime.utcnow(), input_time)
>>> tz = pytz.timezone('America/Montevideo')
>>> str(utc_dt.replace(tzinfo=pytz.utc).astimezone(tz))
'2015-01-24 18:45:00-02:00'
Note: the current offset is 2 hours, not 3. Uruguay observes DST from October till March.