string to time with python - python

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.

Related

How can I convert from UTC time to local time in python?

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

Python: Add or remove timezone hours from a timestamp and get actual time

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)

unable to display time in different timezone

When I change tzinfo on an aware datetime instance I keep getting the same strftime result:
>>> from datetime import datetime
>>> import pytz
>>> fmt = '%d.%m.%Y %H:%M'
>>> now_naive = datetime.utcnow()
>>> now_naive.strftime(fmt)
'02.08.2017 11:53'
>>> now_aware = now_naive.replace(tzinfo=pytz.timezone('UTC'))
>>> now_aware_minus_3 = now_aware.replace(tzinfo=pytz.timezone('Etc/GMT-3'))
>>> now_aware.strftime(fmt)
'02.08.2017 11:53'
>>> now_aware_minus_3.strftime(fmt)
'02.08.2017 11:53'
Why is that? how do I display current time in different timezone?
Try it in this way :
from datetime import datetime
from pytz import timezone
x=datetime.now(timezone('Europe/Madrid'))
print x
x=datetime.now(timezone('UTC'))
print x
x=datetime.now(timezone('Etc/GMT-3'))
print x
Using .replace(tzinfo=...) only replaces the timezone in the datetime object, without performing an actual timezone conversion.
Try this instead:
time_unaware = datetime.utcnow()
time_utc = pytz.timezone('UTC').localize(time_unaware) # same as .replace(tzinfo=...)
time_gmt_minus_3 = time_utc.astimezone(pytz.timezone('Etc/GMT-3')) # performs timezone conversion
Using .strftime() on time_gmt_minus_3 should now show what you expected.
Also, #sophros has linked here:
In order to conform with the POSIX style, those zones beginning with "Etc/GMT" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign.

Easy way to get date from UTC to PST in python 2.7.x

I have this:
>>> import datetime
>>> today = str(datetime.date.today())
>>> print today
2017-06-07
The machine is in UTC time. I would like to know if there is easy/simple way to get same kind of output for PST (without changing machine time zone).
import datetime
import pytz
def tz2ntz(date_obj, tz, ntz):
# date_obj: datetime object
# tz: old timezone
# ntz: new timezone
if isinstance(date_obj, datetime.date) and tz and ntz:
date_obj = date_obj.replace(tzinfo=pytz.timezone(tz))
return date_obj.astimezone(pytz.timezone(ntz))
return False
print tz2ntz(datetime.datetime.utcnow(), 'UTC', 'US/Pacific')

Python date string manipulation based on timezone - DST

My objective is to take string(containg UTC date and time) as the input and convert it to local timezone based on Timezone difference. I have come up with the following code
Code
import time
print "Timezone Diff", time.timezone/3600
def convertTime(string):
print "Before Conversion"
print "year",string[0:4],"month",string[5:7],"day",string[8:10]
print "hour",string[11:13],"min",string[14:16]
print "After Conversion"
print "newhour",int(string[11:13])-(time.timezone/3600)
newhour = int(string[11:13])-(time.timezone/3600)
if newhour>=24:
print "year",string[0:4],"month",string[5:7],"newday",int(string[8:10])+1
print "hour",newhour-24,"min",string[14:16]
convertTime('2013:07:04:14:00')
Output:
Timezone Diff -10
Before Conversion
year 2013 month 07 day 04
hour 14 min 00
After Conversion
newhour 24
year 2013 month 07 newday 5
hour 0 min 00
This code is very basic , and clearly wouldn't work for month /year changes and not consider leap years. Can anyone suggest me a better approach to this issue.
Here's a solution with the datetime and pytz modules, using my timezone as an example:
import pytz
import datetime
s = '2013:07:04:14:00'
mydate = datetime.datetime.strptime(s, '%Y:%m:%d:%H:%M')
mydate = mydate.replace(tzinfo=timezone('Australia/Sydney'))
print mydate
Prints:
2013-07-04 14:00:00+10:00
You may have to "reshape" the code to work for your exact output, but I hope this helps in any way!
To convert UTC time to a local timezone using only stdlib, you could use an intermediate timestamp value:
from datetime import datetime
def convertTime(timestring):
utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M')
timestamp = (utc_dt - datetime.utcfromtimestamp(0)).total_seconds()
return datetime.fromtimestamp(timestamp) # return datetime in local timezone
See How to convert a python utc datetime to a local datetime using only python standard library?.
To support past dates that have different utc offsets, you might need pytz, tzlocal libraries (stdlib-only solution works fine on Ubuntu; pytz-based solution should also enable Windows support):
from datetime import datetime
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal
# get local timezone
local_tz = get_localzone()
def convertTime(timestring):
utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M')
# return naive datetime object in local timezone
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
#NOTE: .normalize might be unnecessary
return local_tz.normalize(local_dt).replace(tzinfo=None)
The below piece of code sorted out the issue for me . Though pytz is probably the best approach to use. But in case you don't have pytz the below solution could be an alternative.
import datetime
def convertTime(timestring):
UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
local_datetime = datetime.datetime.strptime(timestring, "%Y:%m:%d:%H:%M")
result_utc_datetime = local_datetime - UTC_OFFSET_TIMEDELTA
print result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
s = '2013:07:07:14:00'
convertTime(s)

Categories