How to convert string datetime to UTC UNIX? - python

I have date in the as string in the following format: 202001010000
I am trying to convert this to UNIX format and get the result in UTC
I did:
import datetime
stime = "202001010000"
print(int(datetime.datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=datetime.timezone.utc).timestamp()))
and this is giving me the output in UNIX, but in CEST format.
With the above code I get: 1577836800 but I want the output to be 1577833200
What is the mistake I am doing?

You're setting time zone to UTC when converting to datetime. But since your input represents time in Germany you want a time zone that is active there. EX:
from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+, can use backports.zoneinfo for older versions
stime = "202001010000"
# stime represents time in Germany so we use time zone
time_zone = ZoneInfo('Europe/Berlin')
# to datetime, with tz set:
dtobj = datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=time_zone)
# unix time
ts = dtobj.timestamp()
print(ts)
# 1577833200.0
# back to datetime, again specify time zone
dtobj = datetime.fromtimestamp(ts, tz=time_zone)
print(dtobj)
# 2020-01-01 00:00:00+01:00
Note that if the input represents the same time zone your OS is configured to use, this works correctly without setting a time zone. But I think it's better to be explicit here, to avoid confusion if you e.g. run this script on a machine configured to use another time zone.

What you're trying to get is 7 hours behind and you cannot do that from your start date. You must push your start date back 1 day and push your hours forward 17. This code will work for you
import datetime
stime = "201912310000"
my_date = datetime.datetime.strptime(stime, "%Y%m%d%H%M")
my_date_utc = my_date.replace(hour=17)
my_timestamp = my_date_utc.timestamp()
print(int(my_timestamp))

Related

how to use strtotime to convert time stamp into unixepoch timestamp

I have a datetime string 2021-10-20 15:42:40+00:00that I obtain via S3
s3_object = s3_resource.Object("testunzipping", "DataPump_10000838.zip")
lastModified = s3_object.last_modified
lastModified = str(lastModified)
I need to convert it into a unixepochtimestamp. I was trying this after reading another SO answer
import datetime
time = datetime.datetime.strtotime(lastModified)
but I get this error:
"type object 'datetime.datetime' has no attribute 'strtotime'"
How else can I convert the str or the datetime object into a unixepochtimestamp?
Using fromisoformat (Python 3.7+):
import datetime
lastModified = "2021-10-20 15:42:40+00:00"
ts = datetime.datetime.fromisoformat(lastModified).timestamp()
print(ts)
# 1634744560.0 # Unix time in seconds
Using strptime:
import datetime
lastModified = "2021-10-20 15:42:40+00:00"
ts = datetime.datetime.strptime(lastModified, "%Y-%m-%d %H:%M:%S%z").timestamp()
print(ts)
# 1634744560.0 # Unix time in seconds
Caveat: the input here has a UTC offset (+00:00), which, if parsed correctly, will give aware datetime. All fine then. If that is not the case (no UTC offset or time zone specified), you'll end up with naive datetime, which Python treats as local time. Thus if you call .timestamp(), it will be converted to UTC first (since Unix time refers to UTC).

Convert unix timestamp in Python to datetime and make 2 Hours behind

I have this code, recieve a unix timestamp from a server which is 2 hours ahead of my time. My time is SAST and theirs is GMT +2.
I convert this timestamp in python to a readable datetime like this
import datetime
unixtimestamp = 1507126064
datetime.datetime.fromtimestamp(unixtimestamp).strftime('%Y-%m-%d %H:%M:%S')
The problem is that this time comes back two hours ahead of me, so what would be the easiest way to minus two hours or make it local time.
With datetime.timedelta object:
from datetime import datetime, timedelta
unix_ts = 1507126064
dt = (datetime.fromtimestamp(unix_ts) - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S')
print(dt)

Convert datetime to unix timestamp in python

When I try to convert from UTC timestamp to normal date and add the right timezone I can't find the way to convert the time back to Unix timestamp.
What am I doing worng?
utc_dt = datetime.utcfromtimestamp(self.__modified_time)
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = utc_dt.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
Central is equal to
2015-10-07 12:45:04+02:00
This is what I have when running the code, and I need to convert the time back to timestamp.
from datetime import datetime
from datetime import timedelta
from calendar import timegm
utc_dt = datetime.utcfromtimestamp(self.__modified_time)
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = utc_dt.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
unix_time_central = timegm(central.timetuple())
To get an aware datetime that represents time in your local timezone that corresponds to the given Unix time (self.__modified_time), you could pass the local timezone to fromtimestamp() directly:
from datetime import datetime
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone() # pytz tzinfo
central = datetime.fromtimestamp(self.__modified_time, local_timezone)
# -> 2015-10-07 12:45:04+02:00
To get the Unix time back in Python 3:
unix_time = central.timestamp()
# -> 1444214704.0
unix_time is equal to self.__modified_time (ignoring floating point errors and "right" timezones). To get the code for Python 2 and more details, see this answer.
Arrow ( http://crsmithdev.com/arrow/ ) appears to be the ultimate Python time-related library
import arrow
ts = arrow.get(1455538441)
# ts -> <Arrow [2016-02-15T12:14:01+00:00]>
ts.timestamp
# 1455538441

Check if the date of a timezone is passed current time

I receive time in the format 12:00 and I also have a timezone in the format <DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>. I want to see, if this date is already passed current time in that timezone.
My current timezone may be different from the timezone I receive, so I use the following:
tz = pytz.timezone('Europe/Paris')
d = parse("14:39").replace(tzinfo=tz)
now = datetime.datetime.now(tz)
print (d - now).total_seconds()
Even though the current time in Paris is 14:39, I still get 6600 seconds. I also tried now = datetime.datetime.replace(tzinfo=tz), but I get -3600 seconds.
What I want is having time in a specified timezone, check whether it passed or not.
What about this:
from datetime import datetime
from dateutil import tz
tz = tz.gettz('Europe/Paris')
now = datetime.now().replace(tzinfo=tz)
d = datetime.strptime("{0}/{1}/{2} 14:39".format(now.year,now.month,now.day), "%Y/%m/%d %H:%M").replace(tzinfo=tz)
print (d-now).total_seconds()
I keep the current time in now, in the Europe/Paris timezone, and also create d in the same timezone. If their difference is negative the date is already passed current time in that timezone.

Python Convert time to UTC format

from django.utils import timezone
time_zone = timezone.get_current_timezone_name() # Gives 'Asia/Kolkata'
date_time = datetime.time(12,30,tzinfo=pytz.timezone(str(time_zone)))
Now I need to convert this time to UTC format and save it in Django model. I am not able to use date_time.astimezone(pytz.timezone('UTC')). How can I convert the time to UTC. Also Back to 'time_zone'.
This is a use case when user type time in a text box and we need to save time time in UTC format. Each user will also select his own time zone that we provide from Django timezone module.
Once the user request back the saved time it must be shown back to him in his selected time zone.
These things are always easier using complete datetime objects, e.g.:
import datetime
import pytz
time_zone = pytz.timezone('Asia/Kolkata')
# get naive date
date = datetime.datetime.now().date()
# get naive time
time = datetime.time(12, 30)
# combite to datetime
date_time = datetime.datetime.combine(date, time)
# make time zone aware
date_time = time_zone.localize(date_time)
# convert to UTC
utc_date_time = date_time.astimezone(pytz.utc)
# get time
utc_time = utc_date_time.time()
print(date_time)
print(utc_date_time)
print(utc_time)
Yields:
2014-07-13 12:30:00+05:30
2014-07-13 07:00:00+00:00
07:00:00
right now for me.
set the timezone to UTC in your settings.py. Get the user input of time and timezone in certain format. Suppose you get the user time as 'Jul-7-2014 12:35PM:30' (consider using date input in your html).
from datetime import datetime, timedelta
// convert the time to standard format
user_date = datetime.strptime('Jul-7-2014 12:35PM:30', '%b-%d-%Y %I:%M%p:%S')
user_date_string = user_date.strftime('%Y-%m-%d %H:%M:%S')
// save the time to model with users timezone
// now when user asks back for his time, add the timezone with timedelta
user_date = datetime.strptime(user_date_string, '%Y-%m-%d %H:%M:%S')
user_date = user_date + timedelta(hours = 5, minutes = 30)
// finally display it
print user_data.strftime('%Y-%m-%d %H:%M:%S')
*this is not considering django inbuild datetime functions which returns datetime object for datetime model field. If implemented that it will be more simple

Categories

Resources