I want to apply timezone for meeting_time.strftime
def format_filename(recording, file_type, recording_type):
uuid = recording['uuid']
topic = recording['topic'].replace('/', ' ').replace(':', '').replace('?', '')
rec_type = recording_type.replace("_", " ").title()
meeting_time = parse(recording['start_time'])
return '{} - {} UTC - {}.{}'.format(
meeting_time.strftime('%Y.%m.%d'), meeting_time.strftime('%H.%M %p'), topic+" - "+rec_type, file_type.lower())
Example of filename I got with code above- 2020.12.02 - 10.00
Filename I want - 2020.12.02 - 13.00
Original code - https://github.com/ricardorodrigues-ca/zoom-recording-downloader
You can use datetime and timedelta.
from datetime import datetime, timedelta
print((datetime.now() + timedelta(hours=3)).strftime('%Y.%m.%d - %H.%M'))
Output
2020.12.02 - 14.39
This will print the time after 3 hours from now.
Take a look at this code:
from datetime import datetime, timedelta
d = '2020.12.02 - 10.00'
result = datetime.strftime(datetime.strptime(d, '%Y.%m.%d - %H.%M') + timedelta(hours=3), '%Y.%m.%d - %H.%M')
The result will be:
'2020.12.02 - 13.00'
If all you want to do is add 3 hours, you can do it as:
new_datetime = datetime.datetime.today() + datetime.timedelta(hours=3)
This adds 3 hours to your previous datetime.
If you want to make use of timezone's, you can find about it in Python's official documentation: https://docs.python.org/3.7/library/datetime.html#datetime.tzinfo
Let us make time conversion in a standard and robust way:
In order to covert time between zones:
1- Spcify the zone in which DateTime was recorded.
2- Convert the scpecified DateTime to the required time zone.
The mentioned steps are explained in the followin example:
from datetime import datetime
from pytz import timezone
# Choose any datetime
datetime_local=datetime(2020,12,2,10,00)
print(datetime_local)
# specifiy/include the time zone in the datetime for example ('Brazil/East') (-3.00)
datetime_brazil = timezone('Brazil/East').localize(datetime_local)
print('Brazil')
print(datetime_brazil)
# Convert it to UTC time zone
datetime_utc = datetime_brazil.astimezone(timezone('Etc/Universal'))
print('UTC')
print(datetime_utc)
# Convert the time to Cairo time zone
datetime_cairo = datetime_brazil.astimezone(timezone('Africa/Cairo'))
print('Cairo')
print(datetime_cairo)
The output
2020-12-02 10:00:00
Brazil
2020-12-02 10:00:00-03:00
UTC
2020-12-02 13:00:00+00:00
Cairo
2020-12-02 15:00:00+02:00
We Can get the list of time zone by the followin code:
import pytz
for tz in pytz.all_timezones:
print(tz)
the output list:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
...
...
Applying the steps mentioned above to the code in the question,
if the recorded DateTime was in Brazil and we want to convert it to UTC so we modify the code as follows:
def format_filename(recording, file_type, recording_type):
uuid = recording['uuid']
topic = recording['topic'].replace('/', ' ').replace(':', '').replace('?', '')
rec_type = recording_type.replace("_", " ").title()
meeting_time = parse(recording['start_time'])
# Start of modification
# Sepcify the local time zone, (localize it)
meeting_timt_local = timezone('Brazil/East').localize(meeting_time)
# Convert specified/localized DateTime to utc
meeting_time_utc = meeting_timt_local.astimezone(timezone('Etc/Universal'))
# return the formated meeting_time in utc
return '{} - {} UTC - {}.{}'.format(
meeting_time_utc.strftime('%Y.%m.%d'), meeting_time_utc.strftime('%H.%M %p'), topic+" - "+rec_type, file_type.lower())
Goog Luck
Related
I want to format timestamp to day -1 but require a format
I am getting day-1 exactly minus 24 hrs but I need from midnight onwards
from datetime import datetime,timedelta
import pytz
partdate=datetime.today().strftime('%Y-%m-%d %H:%M:%S')
# print(partdate)
# import pytz
tzinfo=pytz.timezone('US/Eastern')
# print(tzinfo)
x=(datetime.now() + timedelta(days=-1)) # Here
tzinfo=pytz.timezone('US/Eastern')
pardate1=tzinfo.localize(datetime.now()+timedelta(days=-1),is_dst=None)
print(pardate1)
#print('x----->',x)
#print('timevalue',tzinfo)
# yesterday = datetime.today() - timedelta(days = 1 )
# print(yesterday)
output is 2022-08-13 20:39:26.232974-04:00
But required output is 2022-08-13T00:00:000Z
IIUC, you want date/time now in a certain time zone, subtract one day, then convert to UTC, then 'floor' that date/time to midnight.
Here's a step-by-step example how you can do that. Note that I use zoneinfo since pytz is deprecated and time zone name "America/New_York" as "US/Eastern" is obsolte as well.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("America/New_York"))
daybefore = now - timedelta(days=1)
daybefore_UTC = daybefore.astimezone(ZoneInfo("UTC"))
daybefore_UTC_midnight = daybefore_UTC.replace(hour=0, minute=0, second=0, microsecond=0)
print(now)
print(daybefore_UTC_midnight)
# 2022-08-15 03:38:42.006215-04:00
# 2022-08-14 00:00:00+00:00
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
recently I discover problem in my database. 3rd party pass the data as a second and I convert this with python to date and store it to DB. But two different Seconds saved as one date.
how can I avoid this?
My code:
import datetime
A = datetime.fromtimestamp(1600194600).strftime("%Y-%m-%d %H:%M:%S")
print('A: ' , A)
B = datetime.fromtimestamp(1600198200).strftime("%Y-%m-%d %H:%M:%S")
print('B: ' , B)
And the Result is:
A: 2020-09-15 23:00:00
B: 2020-09-15 23:00:00
You can explicitly convert to UTC (aware datetime) by setting the tz argument when calling datetime.fromtimestamp. Ex:
from datetime import datetime, timezone
# Unix time / seconds since the epoch refers to UTC:
A = datetime.fromtimestamp(1600194600, tz=timezone.utc)
B = datetime.fromtimestamp(1600198200, tz=timezone.utc)
print(A.isoformat(' '))
print(B.isoformat(' '))
>>> 2020-09-15 18:30:00+00:00
>>> 2020-09-15 19:30:00+00:00
Now you can convert to a certain time zone, e.g.
from zoneinfo import ZoneInfo # Python 3.9+, for older versions use e.g. backports.zoneinfo
zone = ZoneInfo('Asia/Tehran')
A = A.astimezone(zone)
B = B.astimezone(zone)
print(A.isoformat(' '), str(A.tzinfo))
print(B.isoformat(' '), str(B.tzinfo))
>>> 2020-09-15 23:00:00+04:30 Asia/Tehran
>>> 2020-09-16 00:00:00+04:30 Asia/Tehran
I am using Python to access the mobile API of some web service and the response contains the following weird Date notation: u'/Date(1409522400000+0200)/' This should be the 1st of September, 2014.
I am not sure which format this is, but I would like to convert this to something readable, i.e. a date or a datetime or Unix time.
Can anybody help me with this?
The time string looks like OData version 2 JSON verbose format for Datetime that may be seen in old ASP.NET or WCF applications:
“/Date(<ticks>[“+” | “-” <offset>])/”
<ticks> = number of milliseconds
since midnight Jan 1, 1970
<offset> = utc offset
#!/usr/bin/env python3
import re
from datetime import datetime, timedelta, timezone
time_string = u"/Date(1409522400000+0200)/"
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
ticks, offset = re.match(r'/Date\((\d+)([+-]\d{4})?\)/$', time_string).groups()
utc_dt = epoch + timedelta(milliseconds=int(ticks))
print(utc_dt)
if offset:
offset = int(offset)
hours, minutes = divmod(abs(offset), 100)
if offset < 0:
hours, minutes = -hours, -minutes
dt = utc_dt.astimezone(timezone(timedelta(hours=hours, minutes=minutes)))
print(dt)
Output
2014-08-31 22:00:00+00:00
2014-09-01 00:00:00+02:00
where timezone is defined here.
you received a (java?) timestamp in milliseconds. you can convert it to something more readable like so:
from datetime import date
d=1409522400000/1000.0 # divide by 1000 to get seconds
print date.fromtimestamp(d) # -> 2014-09-01
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.