I'm trying to convert UTC time to Europe/Warsaw time. Warsaw time is now UTC + 2 hours. I don't know why I get result with time 30 minutes eariler. I'm parsing date from string similar to: 7:27:02 AM or 2:16:28 PM.
print(time_str) #6:47:46 PM
format = '%I:%M:%S %p'
time_obj = datetime.strptime(time_str, format)
utc_time = time_obj.replace(tzinfo=ZoneInfo('Etc/UTC'))
converted_time = utc_time.astimezone(tz=ZoneInfo('Europe/Warsaw')).time()
print(utc_time.time(), converted_time)
Output is
6:47:46 PM
18:47:46
20:11:46
While I expect:
6:47:46 PM
18:47:46
20:47:46
EDIT - this line fixed it:
time_obj = datetime.strptime(time_str, format).replace(year=2021, month=7, day=14)
Related
I am having an input as:
test_date = 2019-06-15 10:16:55-06:00
the code to convert is:
new_value= datetime.strptime(test_date, '%a, %d %b %Y %H:%M:%S GMT')
After getting the value from new_value> I need to convert it to:
new_date = new_value.strftime("%m/%d/%Y %I:%M:%S %p")
But I am getting an error as below:
TypeError: strptime() argument 1 must be str, not datetime.datetime
When I try to convert test_date as string like str(test_date). It causes
ValueError: time data '2019-06-15 10:16:55-06:00' does not match format '%a, %d %b %Y %H:%M:%S GMT'
How can I achieve this?
%a refers to weekday like Sun, Mon, ..., etc, but it does not appear in your test_date input. Therefore it raises an error. -06:00 means Central Standard Time, e.g. in United states, Chicago. Try the following instead.
from datetime import datetime
test_date = '2019-06-15 10:16:55-06:00'
new_value = datetime.strptime(test_date, '%Y-%m-%d %H:%M:%S%z')
new_value = new_value.timestamp()
new_value = datetime.utcfromtimestamp(new_value) #change from CST to GMT
new_date = new_value.strftime("%m/%d/%Y %I:%M:%S %p")
print(new_date)
06/15/2019 04:16:55 PM
You need to specify you date format at strptime to parse date correctly.
Then you need to convert date to GMT timezone like this
from datetime import datetime
test_date = '2019-06-15 10:16:55-06:00'
new_value = datetime.strptime(test_date, '%Y-%m-%d %H:%M:%S%z')
new_value_timestamp = new_value.timestamp()
gmt_date = datetime.utcfromtimestamp(new_value_timestamp)
new_date = gmt_date.strftime("%m/%d/%Y %I:%M:%S %p")
print(new_date)
Output
06/15/2019 04:16:55 PM
from datetime import datetime
date_string = "21-June-2018"
date_string1 = "2019-06-21 10:16:55-0600"
print("date_string =", date_string)
print("type of date_string =", type(date_string))
date_object = datetime.strptime(date_string, "%d-%B-%Y")
date_object1 = datetime.strptime(date_string1, "%Y-%m-%d %H:%M:%S%z")
print("date_object =", date_object)
print("date_object1 =", date_object1)
print("type of date_object =", type(date_object))
new_value= test_date.strftime("%d %b %Y %H:%M:%S GMT")
new_date = datetime.strptime(new_value,'%d %b %Y %H:%M:%S %Z')
new_date will give you the output.
I want to convert a string to a datetime class object, but for some reason the PM and AM does not effect the final result. What I want is that if it is PM, 12h would be added to the hours
Format → %d/%m/%Y %H:%M:%S %p
Example → 12/11/2020 8:25:52 PM
Problem:
import datetime as tm
ts = tm.datetime.strptime('12/11/2020 8:25:52 AM', '%d/%m/%Y %H:%M:%S %p')
ts2 = tm.datetime.strptime('12/11/2020 8:25:52 PM', '%d/%m/%Y %H:%M:%S %p')
print(ts2)
print(ts == ts2)
Output:
2020-11-12 08:25:52
True
It works just fine if you change the %H to %I since %H is is the "24-hour" format,
import datetime as tm
ts = tm.datetime.strptime('12/11/2020 8:25:52 AM', '%d/%m/%Y %I:%M:%S %p')
ts2 = tm.datetime.strptime('12/11/2020 8:25:52 PM', '%d/%m/%Y %I:%M:%S %p')
print(ts2)
print(ts == ts2)
I want to get start time and end time of yesterday linux timestamp
import time
startDay = time.strftime('%Y-%m-%d 00:00:00')
print startDay
endDay =time.strftime('%Y-%m-%d 23:59:59')
print endDay
Output is:
2016-11-18 00:00:00
2016-11-18 23:59:59
this showing in string today start-time and end-time
I want to get yesterday start-time and end-time in linux time-stamp
like:
4319395200
4319481599
import time
def datetime_timestamp(dt):
time.strptime(dt, '%Y-%m-%d %H:%M:%S')
s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
return int(s)
import datetime
midnight2 = datetime.datetime.now().replace(hour=0,minute=0,second=0, microsecond=0)
midnight2 = midnight2 - datetime.timedelta(seconds= +1)
midnight1 = midnight2 - datetime.timedelta(days= +1, seconds= -1)
base = datetime.datetime.fromtimestamp(0)
yesterday = (midnight1 - base).total_seconds()
thismorning = (midnight2 - base).total_seconds()
print midnight1,"timestamp",int(yesterday)
print midnight2,"timestamp",int(thismorning)
print "Seconds elapsed",thismorning - yesterday
Result as of 18/11/2016 :
2016-11-17 00:00:00 timestamp 1479337200
2016-11-17 23:59:59 timestamp 1479423599
Seconds elapsed 86399.0
from datetime import datetime, date, time, timedelta
# get start of today
dt = datetime.combine(date.today(), time(0, 0, 0))
# start of yesterday = one day before start of today
sday_timestamp = int((dt - timedelta(days=1)).timestamp())
# end of yesterday = one second before start of today
eday_timestamp = int((dt - timedelta(seconds=1)).timestamp())
print(sday_timestamp)
print(eday_timestamp)
Or:
# get timestamp of start of today
dt_timestamp = int(datetime.combine(date.today(), time(0, 0, 0)).timestamp())
# start of yesterday = start of today - 86400 seconds
sday_timestamp = dt_timestamp - 86400
# end of yesterday = start of today - 1 second
eday_timestamp = dt_timestamp - 1
Use the power of perl command , no need to import time.
Startday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 00:00:00",localtime time-86400;')
Endday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 23:59:59",localtime time-86400;')
echo $Startday
echo $Endday
or
startday=date --date='1 day ago' +%Y%m%d\t00:00:00
startday=date --date='1 day ago' +%Y%m%d\t23:59:59
echo $Startday
echo $Endday
I use this code to format my time but the time that comes out is 5 hours wrong. I should be 06 something in calcutta now and it formats the time now as 01... something. What is wrong with the code?
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
tzinfo = timezone(timezoneinfo)
month = MONTHS[to_format.month - 1]
input = pytz.timezone(timezoneinfo).localize(
datetime(int(to_format.year), int(to_format.month), int(to_format.day), int(to_format.hour), int(to_format.minute)))
date_str = '{0} {1}'.format(input.day, _(month))
time_str = format_time(input, 'H:mm', tzinfo=tzinfo, locale=locale)
return "{0} {1}".format(date_str, time_str)
Update
This code worked which was according to the answer below.
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
import datetime as DT
import pytz
utc = pytz.utc
to_format = DT.datetime(int(to_format.year), int(to_format.month), int(to_format.day), int(to_format.hour), int(to_format.minute))
utc_date = utc.localize(to_format)
tzone = pytz.timezone(timezoneinfo)
tzone_date = utc_date.astimezone(tzone)
month = MONTHS[int(tzone_date.month) - 1]
time_str = format_time(tzone_date, 'H:mm')
date_str = '{0} {1}'.format(tzone_date.day, _(month))
return "{0} {1}".format(date_str, time_str)
It sounds like to_format is a naive datetime in UTC time.
You want to convert it to Calcutta time.
To do this, you localize to_format to UTC time1, and then use astimezone to convert that timezone-aware time to Calcutta time:
import datetime as DT
import pytz
utc = pytz.utc
to_format = DT.datetime(2015,7,17,1,0)
print(to_format)
# 2015-07-17 01:00:00
utc_date = utc.localize(to_format)
print(utc_date)
# 2015-07-17 01:00:00+00:00
timezoneinfo = 'Asia/Calcutta'
tzone = pytz.timezone(timezoneinfo)
tzone_date = utc_date.astimezone(tzone)
print(tzone_date)
# 2015-07-17 06:30:00+05:30
1The tzone.localize method does not convert between timezones. It
interprets the given localtime as one given in tzone. So if to_format is
meant to be interpreted as a UTC time, then use utc.localize to convert the
naive datetime to a timezone-aware UTC time.
A specific bank has branches in all major cities in the world. They all open at 10:00 AM local time. If within a timezone that uses DST, then of course the local opening time also follows the DST-adjusted time. So how do I go from the local time to the utc time.
What I need is a function to_utc(localdt, tz) like this:
Arguments:
localdt: localtime, as naive datetime object, DST-adjusted
tz: timezone in the TZ-format, e.g. 'Europe/Berlin'
Returns:
datetime object, in UTC, timezone-aware
EDIT:
The biggest challenge is to detect whether the local time is in a period with DST, which also means that it is DST adjusted.
For 'Europe/Berlin' which has +1 DST in the summer:
Jan 1st 10:00 => Jan 1st 9:00 UTC
July 1st 10:00 => July 1st 8:00 UTC
For 'Africa/Lagos' which has no DST:
Jan 1st 10:00 => Jan 1st 9:00 UTC
July 1st 10:00 => July 1st 9:00 UTC
Using pytz, and in particular its localize method:
import pytz
import datetime as dt
def to_utc(localdt,tz):
timezone=pytz.timezone(tz)
utc=pytz.utc
return timezone.localize(localdt).astimezone(utc)
if __name__=='__main__':
for tz in ('Europe/Berlin','Africa/Lagos'):
for date in (dt.datetime(2011,1,1,10,0,0),
dt.datetime(2011,7,1,10,0,0),
):
print('{tz:15} {l} --> {u}'.format(
tz=tz,
l=date.strftime('%b %d %H:%M'),
u=to_utc(date,tz).strftime('%b %d %H:%M %Z')))
yields
Europe/Berlin Jan 01 10:00 --> Jan 01 09:00 UTC
Europe/Berlin Jul 01 10:00 --> Jul 01 08:00 UTC
Africa/Lagos Jan 01 10:00 --> Jan 01 09:00 UTC
Africa/Lagos Jul 01 10:00 --> Jul 01 09:00 UTC
from datetime import datetime, tzinfo, timedelta
class GMT1(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=1)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "Europe/Prague"
year, month, day = 2011, 7, 23
dt = datetime(year, month, day, 10)
class UTC(tzinfo):
def utcoffset(self, dt):
return timedelta(0)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "UTC"
def utc(localt, tz):
return localt.replace(tzinfo=tz).astimezone(UTC())
print utc(dt, GMT1())
New Version. This does what you want -- takes a naive datetime and a timezone and returns a UTC datetime.