converting time given from user input to utc - python

I want to convert a time given from user to UTC/RFC 3339 format.
For example, if they gave the string 2022-07-20 1:09:51 I want it to print it 2022-07-20T20:08:51Z. I got how to do it if given the posix time but dont understand how to do it given a string in the above format
Users in pacific time zone

Parse the input, set the timezone, convert to UTC, then format the output.
from datetime import datetime
from zoneinfo import ZoneInfo
# May need to "pip install tzdata" for latest timezone support.
# It is used by ZoneInfo. See https://docs.python.org/3/library/zoneinfo.html
UTC = ZoneInfo('UTC')
LOCAL = ZoneInfo('US/Pacific')
s = '2022-07-20 1:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
local = dt.replace(tzinfo=LOCAL)
utc = local.astimezone(UTC)
print('naive ',dt)
print('local ',local)
print('UTC ',utc)
print('ISO ',utc.isoformat())
print('custom',utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
Output:
naive 2022-07-20 01:09:51
local 2022-07-20 01:09:51-07:00
UTC 2022-07-20 08:09:51+00:00
ISO 2022-07-20T08:09:51+00:00
custom 2022-07-20T08:09:51Z
If you want PM as you implied use either:
s = '2022-07-20 1:09:51pm'
dt = datetime.strptime(s, '%Y-%m-%d %I:%M:%S%p')
or
s = '2022-07-20 13:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
To get a final result of:
custom 2022-07-20T20:09:51Z

Related

facing difficulties converting utc timezone to local

I am getting date and time like this
date_time = "2022-02-17 08:29:36.345374"
And to convert these to AM, PM format I am doing something like this
date_formate = datetime.fromisoformat(date_time).strftime('%d/%m/%Y %I:%M %p')
but End time I am getting is in not local time seems it's in UTC , I am trying to convert it in utc but no luck doing something like this
dtUTC = datetime.fromisoformat(date_formate[:-1])
dtZone = dtUTC.astimezone()
print(dtZone.isoformat(timespec='seconds'))
got this solution on stackoverflow but getting error Invalid isoformat string: '2022-02-17 08:29:36.345374'
Python assumes local time by default if you don't specify a time zone / UTC offset. So in this case, you need to set UTC first, then convert, then format (if you want a string as output):
from datetime import datetime, timezone
date_time = "2022-02-17 08:29:36.345374" # UTC is not specified here...
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone()
print(local) # my tz was on UTC+1 at that date...
# 2022-02-17 09:29:36.345374+01:00
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
If astimezone(None) does not work, you can try tzlocal;
import tzlocal
zone = tzlocal.get_localzone()
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 09:29 AM
or derive a timezone object from a timedelta, e.g.
from datetime import timedelta
zone = timezone(timedelta(minutes=-300)) # UTC-5 hours
local = datetime.fromisoformat(date_time).replace(tzinfo=timezone.utc).astimezone(zone)
local_formatted = local.strftime('%d/%m/%Y %I:%M %p')
print(local_formatted)
# 17/02/2022 03:29 AM

Subtract datetime in python, understanding formats

Given I have a timestamp:
date_time_str = '2019-09-10T13:48:06+0200'
How can I calculate the time difference between the current time and this datetime?
I've got it so far with an impression of strong wrongdoing - this should be possible in a far simpler way:
from datetime import datetime, timezone
import time
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
now = datetime.now()
now_time = now.strftime(format)
print(now_time)
now=datetime.strptime(datetime.fromtimestamp(int(time.time()), tz=timezone.utc).isoformat(), format)
print("now is: %s" % now)
print(now-time_obj)
The above program does not work because the current time comes out in a slightly different formatting:
'2019-09-10T15:56:11+00:00'
That is, if you run the above script for example Python 3.6.5, you get the error:
ValueError: time data '2019-09-10T18:18:09+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
The mismatch is in the timezone format, "+00:00" vs. "+0200".
You can use datetime.now() to get the current datetime in utc:
# Same as your code
from datetime import datetime, timezone
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
# Added:
print(datetime.now(tz=timezone.utc))
# 2019-09-10 18:35:48.066548+00:00
print(datetime.now(tz=timezone.utc) - date_time_obj)
# 6:47:42.066548

converting local time to UTC time(datetime object)

I am trying to convert the local time to "UTC" time.
Followed this guide: How do I convert local time to UTC in Python?
But issue here is with the type of date which we giving here.
import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)
In the above code input is "2001-2-3 10:11:12" (string), But in my case it will be a datetime object.
begin = begin.replace(hour=0, minute=0, second=0, microsecond=0)
Someone let me know how we can achieve the conversion here.
Your string format needs a bit of a modification. You just need the leading zeros in your month and day:
import pytz, datetime
local = pytz.timezone("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-02-03 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive)
utc_dt = local_dt.astimezone(pytz.utc)
If your input (begin) is not a time string but it is a naive (no timezone info) datetime object already then drop datetime.strptime() line (that parses the time string into datetime object) from the example. To convert a given naive datetime object that represents local time to utc:
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone()
local_dt = local_timezone.localize(begin, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

Convert microseconds into format string with timezone

I need to convert a value in microseconds to the format '%Y-%m-%d %H:%M:%S' and apply timezone information to adjust the output. I tried:
datatime.datetime.fromtimestamp(timestamp).strftime('format')
but that is not timezone aware. How do I apply timezone information when converting from microseconds to a date and time string?
To convert the timestamp ("seconds since the epoch") to time in UTC as a naive datetime object:
#!/usr/bin/env python
from datetime import datetime
timestamp = 1422025533
utc_time = datetime.utcfromtimestamp(timestamp)
print("Time is = %s" % utc_time)
# -> Time is = 2015-01-23 15:05:33
If you want to get the value in a specific timezone as an aware datetime object; you should use pytz module:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
tz = pytz.timezone('Europe/London')
timestamp = 1422025533
london_time = datetime.fromtimestamp(timestamp, tz)
print("Time is = %s" % london_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> Time is = 2015-01-23 15:05:33 GMT+0000
I think Delorean is the right lib you should use.
Delorean is a library for clearing up the inconvenient truths that arise dealing with datetimes in
from datetime import datetime
from pytz import timezone
EST = "US/Eastern"
UTC = "UTC"
d = datetime.utcnow()
utc = timezone(UTC)
est = timezone(EST)
d = utc.localize(d)
d = est.normalize(d)
print d

python: convert date timestamp to epoch unix time and figure out number of days remaining?

I want to convert 2014-08-14 20:01:28.242 into a unix timestamp 245293529385 and subtract this by the current timestamp in order to figure out how many days have past and are ultimately remaining by subtracting this value from 14.
Scenario: user signs up and I want to count down the number of days remaining in their trial.
time.strptime to the rescue! Use the format string %Y-%m-%d %H:%M:%S.%f. For example:
import time
t = '2014-08-14 20:01:28.242'
ts = time.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
timestamp = time.mktime(ts)
Now to convert it to a datetime (from: How do you convert a Python time.struct_time object into a datetime object? ):
from datetime import datetime
dt = datetime.fromtimestamp(timestamp)
There are two parts:
Convert input time string into datetime object
#!/usr/bin/env python
from datetime import datetime
dt = datetime.strptime('2014-08-14 20:01:28.242', '%Y-%m-%d %H:%M:%S.%f')
Convert datetime object to Unix time ("seconds since epoch")
The result depends on what time zone is used for the input time e.g., if the input is in UTC then the corresponding POSIX timestamp is:
timestamp = (dt - datetime(1970,1,1)).total_seconds()
# -> 1408046488.242
If your input is in the local timezone then see How do I convert local time to UTC in Python?

Categories

Resources