How to Remove the Zone from a Datetime Value

How can I remove the zone from a DateTime value?

Time always has a zone (it has no meaning without one). You can choose to ignore it when printing by using DateTime#strftime:

now = DateTime.now
puts now
#=> 2012-02-03T10:01:24-07:00

puts now.strftime('%a, %d %b %Y %H:%M:%S')
#=> Fri, 03 Feb 2012 10:01:24

See Time#strftime for the arcane codes used to construct a particular format.

Alternatively, you may wish to convert your DateTime to UTC for a more general representation.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

remove the local timezone from a date in javascript?

I believe d.toDateString() will output the format you're looking for.

var d = new Date();
d.setTime(1432851021000);
d.toDateString(); // outputs to "Thu May 28 2015"
d.toGMTString(); //outputs to "Thu, 28 May 2015 22:10:21 GMT"

Or even d.toLocaleString()
"5/28/2015, 6:10:21 PM"

There are lots of methods available to Date()

How to remove timezone from a Timestamp column in a pandas dataframe

The column must be a datetime dtype, for example after using pd.to_datetime.
Then, you can use tz_localize to change the time zone, a naive timestamp corresponds to time zone None:

testdata['time'].dt.tz_localize(None)

Unless the column is an index (DatetimeIndex), the .dt accessor must be used to access pandas datetime functions.

How to remove timezone from datetime object?

YOu need to assign the dt.replace to a new variable:

In [8]: dt = datetime.now()
...: dt = dt.astimezone(timezone.utc)
...: dt1= dt.replace(tzinfo=None)

In [9]: dt1
Out[9]: datetime.datetime(2020, 4, 19, 12, 59, 56, 439648)

In [10]: dt
Out[10]: datetime.datetime(2020, 4, 19, 12, 59, 56, 439648, tzinfo=datetime.timezone.utc)

Remove timezone information from datetime object

use strftime if you already have a datetime object

dt.strftime('%Y-%m-%d %H:%M:%S')

If you need a datetime object from a string, the fastest way is to use strptime and a slice:

st = '2016-12-14 15:57:16.140645'
dt = datetime.strptime(st[:19], '%Y-%m-%d %H:%M:%S')

Remove Time Zone Offset from DateTimeOffset?

The issue doesn't have anything to do with the database actually. If you set a breakpoint or log the output somewhere, you should be able to see the offset being tacked on shortly after this code:

testDateAndTime = testDateAndTime.DateTime.Date;

Let's break this down:

  • You started with a DateTimeOffset value of 2008-05-01T08:06:32+01:00
  • You then called .DateTime, which resulted in a DateTime value of 2008-05-01T08:06:32 with DateTimeKind.Unspecified.
  • You then called .Date, which resulted in a DateTime value of 2008-05-01T00:00:00 with DateTimeKind.Unspecified.
  • You assign the result back to testDateAndTime, which is of type DateTimeOffset. This invokes an implicit cast from DateTime to DateTimeOffset - which applies the local time zone. In your case, it would appear the offset for this value in your local time zone is -04:00, so the resulting value is a DateTimeOffset of 2008-05-01T00:00:00-04:00, as you described.

You said:

End goal is just to have a date without time or time zone offset.

Well, there is currently no native C# data type that is just a date without a time. There is a pure Date type in the System.Time package in corefxlab, but that's not quite ready for the typical production application. There's LocalDate in the Noda Time library that you can use today, but you'd still have to convert back to a native type before saving to the database. So in the meantime, the best you can do is:

  • Change your SQL Server to use a date type in the field.
  • In your .NET code, use a DateTime with a time of 00:00:00 and DateTimeKind.Unspecified. You'll have to remember to ignore the time portion (as there are indeed dates without a local midnight in certain time zones).
  • Change your test prop to be a DateTime, not a DateTimeOffset.

In general, while DateTimeOffset fits a large number of scenarios (such as timestamping events), it doesn't fit well for date-only values.

I want the current date, with zero offset.

If you really want this as a DateTimeOffset, you'd do:

testDateAndTime = new DateTimeOffset(testDateAndTime.Date, TimeSpan.Zero);

However, I advise against this. By doing so, you're taking the local date of the original value and asserting that it is in UTC. If the original offset is anything other than zero, that would be a false assertion. It is bound to lead to other errors later, as you're actually talking about a different point in time (with potentially a different date) than the one you created.

Regarding the additional question asked in your edit - Specifying DateTimeKind.Utc changes the behavior of the implicit cast. Instead of using the local time zone, it uses UTC time, which always has an offset of zero. The result is the same as the more explicit form I gave above. I still recommend against this, for the same reasons.

Consider an example of starting with 2016-12-31T22:00:00-04:00. By your approach, you'd save into the database 2016-12-31T00:00:00+00:00. However these are two very different points in time. The first one normalized to UTC would be 2017-01-01T02:00:00+00:00, and the second one converted to the other time zone would be 2016-12-30T20:00:00-04:00. Notice the change of dates in the conversion. This is probably not the behavior you'd want creeping into your application.

How to remove the additional time-zone added information from datetime string

You can explicitly state your format via strftime

>>> new = ind.astimezone(indian).replace(microsecond=0)
>>> new.strftime('%Y %m %d %H:%M:%S')
'2019 07 30 16:59:56'

Remove timezone (+01:00) from DateTime

In the first line, the parameter utc=True is not necessary as it converts the input to UTC (subtracting one hour in your case).

In the second line, I get an AttributeError: 'Timestamp' object has no attribute 'dt'. Be aware that to_datetime can return different objects depending on the input.

So the following works for me (using a Timestamp object):

mood['response_time'] = '2019-02-21 15:31:37+01:00'
# Convert to date
mood['response_time'] = pd.to_datetime(mood['response_time'])
# Remove +01:00
mood['response_time'] = mood['response_time'].strftime('%Y-%m-%d %H:%M:%S')
# -> '2019-02-21 15:31:37'


Related Topics



Leave a reply



Submit