datetime
python
truncate
programming
tutorial

How to truncate the time on a datetime object?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Truncating the time on a datetime object means removing the time component (hours, minutes, seconds, microseconds) and keeping only the date, effectively setting the time to midnight (00:00:00). This is useful for date-only comparisons, grouping records by day, and generating daily reports. Python offers several approaches: the .date() method (returns a date object), the .replace() method (returns a datetime at midnight), and datetime.combine(). Other languages have similar patterns.

Python: Using .date()

python
1from datetime import datetime
2
3dt = datetime(2025, 3, 15, 14, 30, 45, 123456)
4
5# Returns a date object (no time component at all)
6date_only = dt.date()
7print(date_only)        # 2025-03-15
8print(type(date_only))  # <class 'datetime.date'>
9
10# Useful for comparison
11other = datetime(2025, 3, 15, 9, 0, 0)
12print(dt.date() == other.date())  # True — same date

Note: .date() returns a date object, not a datetime. If you need a datetime at midnight, use .replace() or combine().

Python: Using .replace()

python
1from datetime import datetime
2
3dt = datetime(2025, 3, 15, 14, 30, 45, 123456)
4
5# Zero out the time components
6truncated = dt.replace(hour=0, minute=0, second=0, microsecond=0)
7print(truncated)        # 2025-03-15 00:00:00
8print(type(truncated))  # <class 'datetime.datetime'>

Python: Using datetime.combine()

python
1from datetime import datetime, time
2
3dt = datetime(2025, 3, 15, 14, 30, 45)
4
5# Combine the date with midnight time
6truncated = datetime.combine(dt.date(), time.min)
7print(truncated)  # 2025-03-15 00:00:00
8
9# time.min is time(0, 0) — midnight

Truncating to Different Precisions

python
1from datetime import datetime
2
3dt = datetime(2025, 3, 15, 14, 37, 45, 123456)
4
5# Truncate to hour (keep date + hour)
6to_hour = dt.replace(minute=0, second=0, microsecond=0)
7print(to_hour)  # 2025-03-15 14:00:00
8
9# Truncate to minute (keep date + hour + minute)
10to_minute = dt.replace(second=0, microsecond=0)
11print(to_minute)  # 2025-03-15 14:37:00
12
13# Truncate to second (remove microseconds only)
14to_second = dt.replace(microsecond=0)
15print(to_second)  # 2025-03-15 14:37:45

Pandas: Truncating DateTime Columns

python
1import pandas as pd
2
3df = pd.DataFrame({
4    'timestamp': pd.to_datetime([
5        '2025-03-15 14:30:45',
6        '2025-03-15 09:15:00',
7        '2025-03-16 22:45:30',
8    ])
9})
10
11# Truncate to date (midnight)
12df['date'] = df['timestamp'].dt.normalize()
13print(df['date'])
14# 0   2025-03-15
15# 1   2025-03-15
16# 2   2025-03-16
17
18# Or use .dt.date for date objects (not datetime)
19df['date_only'] = df['timestamp'].dt.date
20
21# Truncate to hour
22df['hour'] = df['timestamp'].dt.floor('h')
23# 0   2025-03-15 14:00:00
24# 1   2025-03-15 09:00:00
25# 2   2025-03-16 22:00:00
26
27# Group by date
28daily_counts = df.groupby(df['timestamp'].dt.date).size()

JavaScript

javascript
1const dt = new Date('2025-03-15T14:30:45.123Z');
2
3// Method 1: Set time components to zero
4const truncated = new Date(dt);
5truncated.setHours(0, 0, 0, 0);
6console.log(truncated);  // 2025-03-15T00:00:00.000 (local time)
7
8// Method 2: Create new Date from date parts
9const dateOnly = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
10console.log(dateOnly);  // 2025-03-15T00:00:00.000 (local time)
11
12// Method 3: String-based (UTC date string)
13const isoDate = dt.toISOString().split('T')[0];
14console.log(isoDate);  // "2025-03-15"

C#

csharp
1DateTime dt = new DateTime(2025, 3, 15, 14, 30, 45);
2
3// .Date property returns midnight of the same day
4DateTime truncated = dt.Date;
5Console.WriteLine(truncated);  // 3/15/2025 12:00:00 AM
6
7// .NET 6+: DateOnly type (no time component)
8DateOnly dateOnly = DateOnly.FromDateTime(dt);
9Console.WriteLine(dateOnly);  // 3/15/2025

Common Pitfalls

  • Using .date() when a datetime is needed: Python's .date() returns a date object which cannot be compared directly to datetime objects or used in datetime arithmetic (timedelta). Use .replace(hour=0, minute=0, second=0, microsecond=0) if you need a datetime at midnight.
  • Time zone issues when truncating: Truncating a UTC datetime and a local datetime to the same date may produce different dates near midnight. 2025-03-15T23:30:00 UTC is 2025-03-16 in UTC+2. Always truncate in the correct time zone context.
  • JavaScript local vs UTC time: setHours(0,0,0,0) uses local time, while toISOString() returns UTC. Truncating in local time and then comparing to UTC timestamps gives wrong results near midnight. Use setUTCHours(0,0,0,0) for UTC truncation.
  • Pandas .dt.date returning Python objects: df['col'].dt.date returns Python date objects, not pandas Timestamp. These cannot be used with pandas datetime operations. Use .dt.normalize() to get midnight Timestamp values instead.
  • Losing timezone info with .replace(): In Python, .replace() on a timezone-aware datetime preserves the timezone. However, datetime.combine(dt.date(), time.min) creates a naive datetime (no timezone) even if the original was timezone-aware. Pass the tzinfo argument: datetime.combine(dt.date(), time.min, tzinfo=dt.tzinfo).

Summary

  • Python: Use .date() for a date object, .replace(hour=0, ...) for a datetime at midnight
  • Use datetime.combine(dt.date(), time.min) as an alternative
  • Pandas: Use .dt.normalize() for midnight or .dt.floor('h') for truncating to hour
  • JavaScript: Use setHours(0,0,0,0) for local time truncation
  • C#: Use .Date property or DateOnly.FromDateTime()
  • Always consider timezone context when truncating near midnight

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.