I want to use Python to convert times to UTC and compare them. In my experiment, the Tokyo time has a deviation and I do not know if it is a mistake of my approach or a bug?
Code
#!/usr/bin/env python3
import datetime
tz = pytz.timezone("Asia/Tokyo")
date = datetime.datetime.strptime(
'12:00',
'%H:%M'
)
date_with_tz = tz.localize(date)
print("Time in Tokyo\t\t: ", date_with_tz.strftime('%H:%M'))
date_as_utc = date_with_tz.astimezone(pytz.utc)
print("Time Tokyo in UTC\t: ", date_as_utc.strftime('%H:%M'))
print("Should 12 (Tokyo) -> 3 (UTC)")
Output
❯ ./time_zone.py
Time in Tokyo : 12:00
Time Tokyo in UTC : 02:41
The UTC time should be 3 and not 2:41 ... what is happening here?
You don't need to use localize in this case.
import datetime, pytz
tokyo = datetime.datetime.now(pytz.timezone("Asia/Tokyo")).replace(hour=12, minute=0, second=0)
utc = tokyo.astimezone(pytz.utc)
print("Time Tokyo:", tokyo.strftime('%H:%M'))
print("Time UTC:", utc.strftime('%H:%M'))
print("Should 12 (Tokyo) -> 3 (UTC)")
Related
I have been exploring the methods and properties in pd.Timestamp, and pd.DatetimeIndex, but so far have not been able to find a way to get the TimeZone that pandas is adopting; like 'US/Eastern' for a US locale system.
One would assume that pandas would adopt the TimeZone specified in the system locale when converting datetime string like '2022-03-03 17:15:00' into Epoch value.
We could find timezone information using the time module:
time.tzname => ('EST','EDT')
I am wondering in pandas, how do we get the default timezone it is adopting ?
I believe its naive and no tz is assumed.
You can of course specify utc=True and then convert to a specific tz.
import pandas as pd
data = {
"START_TIME": ["2022-06-27 09:30:19", "2022-08-20 11:55:25"],
"STOP_TIME": ["2022-06-27 12:30:00", "2022-08-20 13:00:00"]
}
df = pd.DataFrame(data)
print(df)
START_TIME STOP_TIME
0 2022-06-27 09:30:19 2022-06-27 12:30:00
1 2022-08-20 11:55:25 2022-08-20 13:00:00
for column in [x for x in df.columns[df.columns.str.contains("time", case=False)]]:
df[column] = (
pd.to_datetime(df[column], utc=True)
.dt.tz_convert("America/New_York")
)
print(df)
START_TIME STOP_TIME
0 2022-06-27 05:30:19-04:00 2022-06-27 08:30:00-04:00
1 2022-08-20 07:55:25-04:00 2022-08-20 09:00:00-04:00
If you know the data is already in a specific tz but it is naive you can also make it tz aware.
for column in [x for x in df.columns[df.columns.str.contains("time", case=False)]]:
df[column] = (
pd.to_datetime(df[column], utc=False)
.dt.tz_localize("America/New_York")
)
print(df)
START_TIME STOP_TIME
0 2022-06-27 09:30:19-04:00 2022-06-27 12:30:00-04:00
1 2022-08-20 11:55:25-04:00 2022-08-20 13:00:00-04:00
paypal is giving me this format '03:00:00 Mar 14, 2023 PDT'. I've tried different solutions but i can't get with the right one. How can i separate each item into a string using python?
Assuming you want a datetime object
from datetime import datetime
time_string = "03:00:00 Mar 14, 2023 PDT"
d = datetime.strptime(time_string[:-4], "%H:%M:%S %b %d, %Y")
or
import parsedatetime as pdt # $ pip3 install parsedatetime
cal = pdt.Calendar()
time_string = "03:00:00 Mar 14, 2023 PDT"
d = cal.parseDT(time_string)[0]
Once you have your datetime, output the part(s) you want using strftime
I have a requirement which has input as 2020-03-21T11:23:50-05:00, and output should be two different variables
covertedutc : 2020-03-21 16:23:50
timezone : -05:00
i have tried without timezone in input variable and below is snippet
import datetime
import pytz
timestring = "2020-03-21T11:23:50"
# Create datetime object
d = datetime.datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%S")
print(d.strftime("%d.%m.%y %H:%M:%S"))
This should do the trick:
from datetime import datetime, timedelta
variable='2020-03-21T11:23:50-05:00'
variable = " ".join(variable.split("T")) #eliminating the "T"
converted = datetime.strptime(variable[:19], '%Y-%m-%d %H:%M:%S') + timedelta(hours=5)
print(f'covertedutc {converted}')
print(f'timezone {variable[19:]}')
Output:
covertedutc 2020-03-21 16:23:50
timezone -05:00
Say for the year of 2020, how do I iterate through the days in the months so that my outcome would be in the following format:
Jan1
Jan2
Jan3
....
Jan31
Feb1
I've tried so many things online but I couldnt find an answer. Please help :(
Both of these methods will handle leap years correctly out of the box.
Using a simple while loop:
from datetime import datetime, timedelta
def iter_days(year):
dt = datetime(year, 1, 1)
while dt.year == year:
yield dt
dt += timedelta(days=1)
Using date rules:
from datetime import datetime
from dateutil.rrule import rrule, DAILY
def iter_days(year):
first_date = datetime(year, 1, 1)
last_date = datetime(year, 12, 31)
return rrule(DAILY, dtstart=first_date, until=last_date)
Both would be used the same:
for dt in iter_days(2020):
print(dt.strftime('%b%-d'))
The format string '%b%-d' will give you the format you specified in your question. I don't know if that was a requirement or not.
This is crude but gets what you want for 2020. You'll need to change 366 to 365 for non-leap-years.
#!/usr/bin/python3
import datetime
startDate = '2020-01-01'
start = datetime.datetime.strptime(startDate, '%Y-%m-%d')
for dayNum in range(0,366):
dayOfYear = start + datetime.timedelta(days=dayNum)
print(dayOfYear.strftime('%b %d, %Y'))
The calendar module offers quite a bit of functionality.
Here is a solution that works for any given year
import calendar as cal
for mi in range(1,13):
_, days = cal.monthrange(2020, mi)
for d in range(1, days+1):
print(cal.month_name[mi], d)
After searching around the web got the below two ways to get the age of a person.
Just curious to Know if there is better synthetic way of calculating & writing it in 3.x version of python.
First way around ...
$ cat birth1.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
import datetime
year = datetime.datetime.now().year # getting current year from the system
year_of_birth = int(input("Enter Your Birth Year: "))
print("You are %i Year Old" % (year - year_of_birth))
The Result produced..
$ ./birth1.py
Enter Your Birth Year: 1981
You are 37 Year Old
Second way around ....
$ cat birth2.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
from datetime import datetime, date
print("Your date of birth (dd/mm/yyyy)")
date_of_birth = datetime.strptime(input("Please Put your age here: "), "%d/%m/%Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print("You are %i Year Old." % (age))
The Result produces..
$ ./birth2.py
Your date of birth (dd/mm/yyyy)
Please Put your age here: 22/09/2015
You are 2 Year Old.
Take advantage of timedelta.
import datetime as dt
def years_ago(start: str):
sec_per_year = 365.24 * 24 * 60 * 60
delta = dt.datetime.now() - dt.datetime.strptime(start, '%d/%m/%Y')
return delta.total_seconds() / sec_per_year
if __name__ == '__main__':
print(int(years_ago(input('What is your date of birth (dd/mm/yyyy) ? '))))